3

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

4

1 回答 1

7

附加您的 .cshtml 文件,其中包含输出您通过 POST 填充的值的代码。

我的页面.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,瞧,页面应该是这样的:

剃刀页面帖子

顺便说一句:属性以大写字母开头

于 2017-08-25T00:41:48.367 回答