In previous article, I mentioned Model validation in ASP.NET Core but in this article, I have mentioned what is model binding and how we can achieve it in ASP.NET Core.

What is Model Binding?

When user submits form from a page, and posted on controller side, then data needs to be extract from HTTP request and needs to be converted into .NET type values (int, string etc), which is done automatically by .NET and this process this is known as Model binding.

Models are basically C# class, which helps us to get data from database or save data in database table, easily.

Example, suppose, we have below url to call

http://localhost:11223/home/student/101

with the following ActionMethod

public IActionMethod student(int id)
{
   var student = db.Student.Where(a=>a.Id == id).FirstorDefault();
   return View(student);
}

then in the above request, the value 101 in the request URL is mapped to the id parameter of the student(int id) action method of the Home Controller.

The MVC Framework will automatically bind the data in the request to the action method parameters by name.

By default, model binding gets data in the form of key-value pairs from the following sources in an HTTP request:

  • Form fields: Values in the FORM in HTTP POST requests.
  • The request body (For controllers that have the [ApiController] attribute.) : this is used in Web API controller to get values.
  • Route data: Values provided by the Routing system.
  • Query string parameters:
  • Uploaded files

For each target parameter or property, the sources are scanned in the order indicated in the preceding list.

Model binding using complex type in ASP.NET Core

Let's take a look at an example using Model binding in ASP.NET Core project using Complex type or you can using Class, in Visual studio.

model-binding-asp-net-core

I have created a new ASP.NET Core MVC project in Visual Studio and then I am adding a new class of Student.cs in Models folder, by right-clicking on it and then selecting "Add" -> select "Class" -> name it "Student.cs"

namespace ModelBindingASPNetCore.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Class { get; set; }
        public bool IsActive { get; set; }
    }
}

Now, you need to navigate to "Views" -> "Home" ->"Index.cshtml" and create a new HTML form inside it

@{
    ViewData["Title"] = "Home Page";
}

<form asp-action="Index" asp-controller="Home" method="post">
    <div class="row">
        <div class="col-6">Id</div>
        <div class="col-6">@Html.TextBox("Id","", new {@class="form-control"})</div>
    </div><br />
     <div class="row">
        <div class="col-6">Name</div>
        <div class="col-6">@Html.TextBox("Name","", new {@class="form-control"})</div>
    </div><br />
     <div class="row">
        <div class="col-6">Class</div>
        <div class="col-6">@Html.TextBox("Class","", new {@class="form-control"})</div>
    </div><br />
     <div class="row">
        <div class="col-6">Active</div>
        <div class="col-6">@Html.CheckBox("IsActive")</div>
    </div><br />
     <div class="row">
        <div class="col-12"><input type="submit" class="btn btn-primary" value="Submit"/></div>
    </div><br />
</form>

In the above HTML code, we are creating HTML forms using Razor syntax, @Html.TextBox("PropertyName"), as it will be converted into it's HTML automatically when page renders.

Now, in our HomeController.cs we need to get values by adding argument in httppost Index ActionMethod, and Controller will automatically bind values to Student user type, using "name" HTML tag of form

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(Student stu)
        {
            // check values are automatically binded when form is submitted
            var id = stu.Id;
            var name = stu.Name;
            var clas = stu.Class;
            var isActive = stu.IsActive;

            //do something with values
            // validate and then save in database
            return View();
        }

That's it, now build your project and run it in browser.

Once you will enter sample values and hit "Submit" button, you will see Controller ActionMethod has got the values correctly mapped for Student type.

Here is gif example.

model-binding-in-asp-net-core-with-example

That's it, we are done, hope it clears your concept of Model binding in ASP.NET Core.

You may also like to read:

File upload using Ajax in ASP.NET Core

Form Submit in ASP.NET Core MVC using Tag Helpers

More than one DBContext was found - EF Core

What is the difference between ASP.NET MVC and ASP.NET Core?