In the ASP.net MVC model, we have an important type of MVC model binding method “HTTP Request”. When a developer sends a request from the web-form browser and from the controller at the same time, the action binding function passes the parameter and performs the middle process of binding the HTTP incoming request with the controller action method.

In this article, we will understand in detail the concept of a Model Binder.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is Model Binding?

ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating .NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.

Data from HTTP requests are used by controllers and Razor pages. Route data, for example, may serve as a record key, while posted form fields may serve as values for model properties. It would be laborious and error-prone to write code to retrieve each of these data and transform them from strings to .NET types. This approach is made easier by model binding. The model binding mechanism is as follows:

  • Data is retrieved from a variety of sources, including route data, form fields, and query strings.
  • In method arguments and public properties, the data is passed to controllers and Razor pages.
  • Converts data from strings to .NET types.
  • Properties of complicated types are updated.

Here is the pictorial representation of Model Binding:

MVC_Model_Binding_1.

When a user performs the HTTP request with web-form data, the application request will redirect to the corresponding Controller Action method and its model. When the request transfers to the controller, the model binder will bind the request with the corresponding action method. According to this model, the binder provides the ways to bind the HTTP request with the corresponding Controller’s Action method and model. It works as an agent between View, Controller, and Model.

ASP.NET MVC implements many alternatives to bind the HTTP request (browser request or web form data) which comes /view’s data to model properties through controller action method.

  • Model binding
  • Form Collection

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

HTTP Request Binding Handling FormCollection in ASP.NET Through mvcFormCollection

The main purpose of FormCollection class is to obtain the web form’s data as input values and bind with the corresponding controller’s action method and model’s data field properties. 

Let us now understand the working method of how web form input data will bind utilizing the Form Collection class.

Step 1: Open the VS 2019 and select the ASP.NET core web application.

MVC_Model_Binding_2.

Step 2: Select the template of the web application (MVC).

MVC_Model_Binding_3

Step 3: Go to the home controller and student basic type binding.

MVC_Model_Binding_4.

Step 4: Create view as per the below given code example:

MVC_Model_Binding_5

Step 5: Now, press f5 and run the solution. It will take you to the output browser window.

MVC_Model_Binding_6

Step 6: Fill in the form details; put the breakpoint to your home controller action method; and hit on the Submit button.

MVC_Model_Binding_7

Step 7: Go to the controller method, and put the cursor on the FormCollections.

MVC_Model_Binding_8

Now, we know that Form Collection carries the form’s data values as per this example.

How Model Binding Works

Model binding is a simplistic way to correlate C# code with an HTTP request. 

The model binding applies to transforming the HTTP request data in the query's form string and form collection of the action method parameters. We can consider these parameters to be primitive type or complex type.

Binding to Primitive Type

The HTTP GET request sets data into a query string. MVC framework transforms a query string to the action method parameters in automatic ways and displays and checks if its names match or not.

For example, we would automatically map the query string id in the subsequent GET request to the Edit() action method's id parameter value.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Binding to Complex Type

Model binding further operates on complex types. It will transform the input field’s data automatically from the view to the features properties of a complex type signature values (parameters) of an action method in HttpPost request if its properties' signatures match with the fields on the view.

Employee Class Example

public class Employee

{

    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public int Org{ get; set; }

    public Employeetype Type{ get; set; }

}

public class Employeetype 

{

    public int EmployeetypeId { get; set; }

    public string EmployeeTypename { get; set; }

}

After defining the class, here we can create the controller, and declare the action method which has the Employee type parameter.

As per the below example, the Edit action method (HttpPost) includes an Employee type parameter.

[HttpPost]

public ActionResult Edit(Employee etd)

{

    var id = etd.EmpId ;

    var name = etd.StudentName;

    var EmpOrg= etd.Org;

    var Employeetype = etd.Employeetype.EmployeeTypename;

    return RedirectToAction("Index");

}

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Searching Parameter for Model Binding

In the MVC framework, we have the concept of searching the parameter using model binding. 

Here, we define the int calls to BindModel function which maps or binds value from the URL of its method parameter. The MVC framework explores four types of locations for its suitable parameters. Once it matches or is found, then the search is complete and the value is processed. The locations for the search are:

  1. Request.Form: Values implemented by the user in HTML form elements
  2. RouteData.Values: Values  collected using the application routes
  3. Request.QueryString: Data incorporated in the query string part of the request URL
  4. Request.Files: where we uploaded its Files as part of the request

Binding Primitive Data Types

It is a process that automatically transforms certain request values into a primitive or complex type object.

We can consider Model Binding as a two-way process. 

  1. It accumulates values from its incoming HTTP request and retrieves or fetches the primitive type or a complex type with certain values.
  2. Value providers are accountable for accumulating values from their requests, and Model Binders are accountable for populating values.

MVC_Model_Binding_9

Example:

Below is the method that is mapped using @RequestMapping. Here we have its arguments with a primitive integer type,

@RequestMapping(value = "/Somethingprocess" , method = RequestMethod.GET) 

public String SomethingProcess(@ModelAttribute("myValue") int myValue) 

// please enter something with "Value". 

}

After running this method, it throws the below error message.

HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [int]: No default constructor found; nested exception is java.lang.NoSuchMethodException: int.()

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Binding to Arrays and Collections

Binding to Arrays

To describe how binding to an array works, here we define a distinct action method that accepts a string array as a parameter:

The model binder locates each item with its name attribute cities and then defines an array that contains its values.

Below is the code example:

    public ActionResult Cities(String[] Cities)

        {

            Cities = Cities ?? new string[0];

            return View();

        }

Binding to Collections

Binding to collections operates as coupling to arrays. Here we have a new action method that allows users to enter the cities, and the type of IList as a list parameter.

Below is the code example:

    public ActionResult Cities(IList<string> Cities)

        {

            Cities = Cities ?? new string[0];

            return View(Cities);

        }

Conclusion

We hope this article helped you understand Model Binding in C#. In this article, we discussed the concept of various types of code structures of Model Binding using MVC C#  which will be helpful to professional developers from Java and .net backgrounds, application architectures, and other learners looking for information on JavaScript events.

Besides the varied specialization courses offered by Simplilearn, you can also sign up on SkillUp platform, a Simplilearn initiative. The platform offers numerous free online courses to help with the basics of multiple programming languages, including JavaScript. You can also opt for our Full-Stack Web Development Certification Course to further enhance your knowledge and accelerate your career.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449