【问题标题】:C# Razor pages BindProperty attribute not workingC# Razor 页面的 BindProperty 属性不起作用
【发布时间】:2019-09-30 03:38:54
【问题描述】:

我开始使用我的第一个 Razor 页面,并且按照一些示例,[BindProperty] 属性不起作用... 我正在使用 MongoDB,所以我没有在我的项目中使用 EntityFramework。

这是我的模型类:

public class Student : BaseModel
{
    public string FirstName;
    public string LastName;
}

[Serializable]
public abstract class BaseModel
{
    [JsonProperty(Order = -2)] // appear first
    [BsonRepresentation(BsonType.ObjectId)]
    public virtual string Id { get; set; }
    [DataType(DataType.DateTime)]
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime CreatedDate;
}

这是我的New.cshtml.cs 代码:

public class NewModel : PageModel
{
    readonly IStudentsCollection studentsCollection;
    [BindProperty]
    public Student Student { get; set; }


    public NewModel(IStudentsCollection studentsCollection)
    {
        this.studentsCollection = studentsCollection;
    }

    public async Task<IActionResult> OnPostAsync()
    {
        await studentsCollection.InsertAsync(Student);
        return RedirectToPage("Index");
    }
}

最后,这是我的New.cshtml 代码:

<div class="row">
    <div class="col-md-4">
        <form method="post">
            <h4>Add New Student</h4>
            <hr />
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Student.FirstName"></label>
                <input asp-for="Student.FirstName" class="form-control" />
                <span asp-validation-for="Student.FirstName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Student.LastName"></label>
                <input asp-for="Student.LastName" class="form-control" />
                <span asp-validation-for="Student.LastName" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-info">Save</button>
        </form>
    </div>
</div>

单击“保存”按钮后,我将进入 OnPostAsync 方法,但 Student 对象具有所有 null 值...

我在这里错过了什么?

【问题讨论】:

    标签: c# asp.net-core razor razor-pages


    【解决方案1】:

    您需要为您的财产提供set 访问器:

    public string FirstName { get; set; }
    public string LastName { get; set; }
    

    【讨论】:

    • 谢谢,它解决了,虽然我认为不指定 getter 和 setter 应该不是问题(即使属性状态为 BindProperty 而不是 BindField)。
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 2020-04-25
    • 2020-07-29
    • 2019-12-16
    • 2019-02-18
    • 2021-01-17
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多