3 c# asp.net razor asp.net-core razor-pages
我正在尝试创建一个简单的asp.net核心剃刀网站。
我有一个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">
}
Run Code Online (Sandbox Code Playgroud)
和一个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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够将年龄和金钱传递给cs文件,然后将其传递回cshtml文件,以便在提交按钮发送get请求后将其显示在页面上。我该如何实施?
更新:以下代码不起作用。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});
}
}
}
Run Code Online (Sandbox Code Playgroud)
和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
Run Code Online (Sandbox Code Playgroud)
无论您键入什么,金钱和年龄在页面和文件上都显示为0。
在.cshtml文件中附加代码,以输出通过POST填充的值。
MyPage.cshtml
@page
@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
Run Code Online (Sandbox Code Playgroud)
现在,将其添加[BindProperty]到模型中的每个属性,您想要从中更新OnPost():
[BindProperty]
public int Age { get; set; }
[BindProperty]
public decimal Money { get; set; }
Run Code Online (Sandbox Code Playgroud)
此外,正如Bart Calixto指出的那样,这些属性必须是公开的,以便您可以从中访问Page。
该OnPost()方法非常简单,因为ASP.NET Core在后台完成所有工作(由于通过进行了绑定[BindProperty])。
public IActionResult OnPost()
{
return Page();
}
Run Code Online (Sandbox Code Playgroud)
因此,现在您可以单击Submit并瞧瞧,页面应如下所示:
| 归档时间: |
|
| 查看次数: |
8539 次 |
| 最近记录: |