【问题标题】:Why this Model Binding not working in Razor Page为什么此模型绑定在 Razor 页面中不起作用
【发布时间】:2022-01-11 08:06:17
【问题描述】:

我正在使用带有简单示例的 ASP.NET Core 3.1 来测试模型绑定以发布表单。要绑定的属性是一个名为“Student”的对象。 Bud 模型绑定不适用于 post 方法。我将不胜感激任何帮助指出这里有什么问题。

这是我的测试程序的代码:

'学生班':

namespace ModelBindPost.Models
{
    public class Student
    {
        public int Id;
        public string FirstName;
        public string LastName;

    }
}

'Edit.cshtml.cs'

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ModelBindPost.Models;

命名空间 ModelBindPost.Pages { 公共类 EditModel : PageModel { [BindProperty(SupportsGet = true)] 公共学生学生{得到;放; }

    public EditModel()
    {
        Student = new Student();
    }

    public IActionResult OnGet()
    {
        Student.Id = 1;
        Student.FirstName = "Jean";
        Student.LastName = "Smith";
        return Page();
    }
    public IActionResult OnPost()
    {
        string name = this.Student.FirstName;
        return Page();
    }


}

}

'Edit.cshtml':

@page
@model ModelBindPost.Pages.EditModel
@{
}

<h2>Model Binding Test</h2>

<form method="post">
<div class="form-group">
    <lable asp-for="Student.Id"></lable>
    <input asp-for="Student.Id" class="form-control" />
</div>
<div class="form-group">
    <lable asp-for="Student.FirstName"></lable>
    <input asp-for="Student.FirstName" class="form-control" />
</div>
<div class="form-group">
    <lable asp-for="Student.LastName"></lable>
    <input asp-for="Student.LastName" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>

【问题讨论】:

    标签: asp.net-core asp.net-core-3.1 model-binding


    【解决方案1】:

    简单的公共字段不能用于模型绑定。您需要添加 getter 和 setter 来创建如下属性:

    public class Student
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
    }
    

    【讨论】:

    • 它解决了这个问题。非常感谢您的帮助!!!
    • 嗨@bedrock,如果我的回答可以帮助您解决问题,您能接受吗?参考:How to accept as answer。谢谢。
    • 答案已被接受。
    猜你喜欢
    • 2021-03-07
    • 2013-05-05
    • 2021-11-13
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2019-01-22
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多