What is model binding in ASP.NET ?

Part I

Introduction

Model binding maps data from HTTP requests to enact method parameters. The parameters might be simple types like strings, integers or floats or some complex types. This is a great attribute of MVC because to map incoming data to a counterpart is a repeated task. MVC solves this problem by abstracting binding away so programmers don’t have to rewrite a slightly different version of the same code in every app.

How does model binding work

When MVC receives an HTTP request, it assigns it to a specific action method of a controller. It desides which action method to run based on what is in the routed data, then it binds values from the HTTP request to that action method’s parameters. For instance, let’s consider the following URL:

http://contoso.com/movies/edit/2

Since the route template looks like this, {controller=Home}/{action=Index}/{id?}, movies/edit/2 routes to the Movies controller, and its Edit method. It also accepts an optional parameter called id. The code for the action method should look something like this:

Copy

C#

public IActionResult Edit(int? id)

Note: The strings in the URL route are not case sensitive.

MVC will bind request data to the action parameters by name. MVC will search for values for every parameter using the parameter name and the names of its public settable properties. In the above instance, the only action parameter is named id, which MVC binds to the value with the same name in the route values. In addition to route values MVC will bind data from various parts of the request and it does not follow any set of orders. We enlist the data sources in a order that model binding looks through them:

  1. Form values: These are form values that go in the HTTP request using the POST method.
  2. Route values: The set of route values provided by Routing
  1. Query strings: The query string part of the URI.

To mention form values, route data, and query strings are all stored as name-value pairs.

Since model binding asked for a key named id and there is nothing named id in the form values, it proceeded to the route values looking for that key. In our example, it’s a match. Binding happens, and the value is converted to the integer 2. The same request if you do by using Edit(string id), this would convert to the string “2”.

So far the example uses simple types. In MVC simple types are any .NET primitive type or type with a string type converter. If the action method’s parameter were a class such as the Movie type, which contains both simple and complex types as properties, MVC’s model binding will still handle it nicely. It uses reflection and recursion to traverse the properties of complex types looking for matches.

In order for binding to occur the class should have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set.

When a parameter is bind, model binding doesn’t go looking for values with that name and it moves forward to bind the next parameter. If binding fails, MVC does not show an error. You can find out model state errors by checking the ModelState.IsValid property.

Note: Each entry in the controller’s ModelState property is a ModelStateEntry containing an Errors property. It’s very rare to query this collection. Use ModelState.IsValid instead.

Additionally, there are some special data types that MVC must consider when performing model binding:

  • IFormFile, IEnumerable<IFormFile>: One or more uploaded files that are part of the HTTP request.
  • CancelationToken: Used to cancel activity in asynchronous controllers.

These types can be bound to action parameters or to properties on a class type.

On the completion of model binding, Validation occurs. The default mode of model binding works good for the most of the development scenarios.

We conclude the discussion here. We shall continue the rest of the discussion in our next article.

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>