Home > database >  Why this Model Binding not working in Razor Page
Why this Model Binding not working in Razor Page

Time:12-08

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 >
    <lable asp-for="Student.Id"></lable>
    <input asp-for="Student.Id"  />
</div>
<div >
    <lable asp-for="Student.FirstName"></lable>
    <input asp-for="Student.FirstName"  />
</div>
<div >
    <lable asp-for="Student.LastName"></lable>
    <input asp-for="Student.LastName"  />
</div>
<button type="submit" >Save</button>
</form>

CodePudding user response:

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; }

}
  • Related