从视图到控制器asp.net核心剃刀页传递数据

我正在尝试创建一个简单的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">
}

和一个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文件,以便在“提交”按钮发送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});

    }
  }
}

和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.

解决方法:

在.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

现在,将[BindProperty]添加到您要从OnPost()更新的模型中的每个属性:

[BindProperty]
public int Age { get; set; }
[BindProperty]
public decimal Money { get; set; }

此外,正如Bart Calixto所指出的那样,这些属性必须是公共的,以便可以从您的Page进行访问.

OnPost()方法非常简单,因为ASP.NET Core在后台完成所有工作(由于通过[BindProperty]进行了绑定).

public IActionResult OnPost()
{
    return Page();
}

因此,现在您可以单击Submit和voila,页面应如下所示:

从视图到控制器asp.net核心剃刀页传递数据

顺便说一句:属性是用capital letter in the beginning编写的.

上一篇:从剃刀视图传递变量(字符串)的值到React组件


下一篇:Razor syntax reference for ASP.NET Core