I am trying to create a simple asp.net core razor web site.
I have a cshtml page:
@page
@using RazorPages
@model IndexModel
@using (Html.BeginForm()) {
<label for="age">How old are you?</label>
<input type="text" asp-for="age">
<br/>
<label for="money">How much money do you have in your pocket?</label>
<input type="text" asp-for="money">
<br/>
<input type="submit" id="Submit">
}
and a cs file:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Threading.Tasks;
namespace RazorPages
{
public class IndexModel : PageModel
{
protected string money { get; set; }
protected string age { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("Index");
}
}
}
I want to be able to pass age and money to the cs file and then pass it back to the cshtml file in order to display it on the page after the submit button sends a get request. How can I implement this?
Updated: The following code does not work. index.cshtml.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Threading.Tasks;
namespace RazorPages
{
public class IndexModel : PageModel
{
[BindProperty]
public decimal Money { get; set; }
[BindProperty]
public int Age { get; set; }
public IActionResult OnPost()
{
/* if (!ModelState.IsValid)
{
return Page();
}*/
this.Money = Money;
this.Age = Age;
System.IO.File.WriteAllText(@"C:\Users\Administrator\Desktop\murach\exercises\WriteText.txt",
this.Money.ToString());
return RedirectToPage("Index", new { age = this.Age, money = this.Money});
}
}
}
and index.cshtml:
@page
@using RazorPages
@model IndexModel
@using (Html.BeginForm()) {
<label for="Age">How old are you?</label>
<input type="text" asp-for="Age">
<br/>
<label for="Money">How much money do you have in your pocket?</label>
<input type="text" asp-for="Money">
<br/>
<input type="submit" id="Submit">
}
Money: @Model.Money
Age: @Model.Age
Money and age show up as 0s on the page and file regardless of what you type in.
Index
page and pass those properties to that Page? – jACModelState
is valid, which means you'll get redirected onPost. – jACPage
, throwing'Page.Age' is inaccessible due to its protection level
– jAC