Search code examples
asp.net-coreasp.net-core-3.1model-binding

Why this Model Binding not working in Razor Page


I am using ASP.NET Core 3.1 with a simple example to test model binding to post a form. The property to be bound is an object named "Student". Bud the model binding is not working with post method. I will appreciate any help to point out what's wrong here.

Here are the code of my test programs:

'Student Class':

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;

namespace ModelBindPost.Pages { public class EditModel : PageModel { [BindProperty(SupportsGet = true)] public Student Student { get; set; }

    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>

Solution

  • A simple public field cannot work for model binding. You need add getter and setter to create property like below:

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