我正在尝试创建一个简单的 asp.net core razor 网站。
我有一个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">
}
和一个cs文件:
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");
}
}
}
我希望能够将年龄和金钱传递给 cs 文件,然后将其传递回 cshtml 文件,以便在提交按钮发送获取请求后将其显示在页面上。我该如何实施?
更新:以下代码不起作用。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});
}
}
}
和 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
无论您输入什么,金钱和年龄在页面和文件上都显示为 0。