Monday 4 March 2013

ASP.NET MVC Model Binding


Model Binding
Model binding is the process of creating .NET objects using the data sent by the browser in an HTTP request. MVC Framework has to map the details of the request in such a way that it can pass appropriate values or objects as parameters to action method using default model binder (DefaultModelBinder).

Default Model Binder:  Action invoker used default model binder when it can’t find a custom binder to bind the type for action method. Default model binder search in following location and order for named parameters data.

Source
Description
Request.Form
Contents HTML form elements data.
RouteData.Values
Application routes values
Request.QueryString
Data in the query string of the request URL
Request.Files
Files that have been uploaded as part of the request.

Example: How to find id parameter

  • Request.Form["id"]
  • RouteData.Values["id"]
  • Request.QueryString["id"]
  • Request.Files["id"]

System.ComponentModel.TypeDescriptor class use to convert request data into parameter type. If value cannot be convertible then default model binder won’t be able to bind to the model.
Default model binder use reflation to bind for complex data type like class.

Bind attribute: We can use the Bind attribute to include or exclude model properties from the binding process.

Example: To include first and last name in person object. Person FirstName and LastName property value will be consider other will ignored.
public ActionResult Register([Bind(Include = "FirstName, LastName")] Person person)

Example: To exclude sex property in person object. Person sex property value will be ignored.
public ActionResult Register([Bind(Exclude = "Sex")] Person person)

Example: Bind attribute at Model level. Policy applied to the model class cannot be overridden by applying a less restrictive policy to the action method parameter.
[Bind(Exclude = "PersonId")]

We can also restrict binding to a specific data source like form collection or file.
Example:
public ActionResult Register(FormCollection form)
public ActionResult Register(HttpPostedFileBase file)

Custom Model Binder: We can create a custom model binder to override default binder for specific types. We can create custom model binder to create a custom class that implements IModelBinder interface or can create a class that inherits from DefaultModelBinder class.

The IModelBinder interface contains a single method BindModel() that allows you to bind model with the form data.

Example:
public class PersonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Person person = new Person();
            person.FirstName = controllerContext.HttpContext.Request.Form["FirstName"];
            person.LastName = controllerContext.HttpContext.Request.Form["LastName"];
            person.FullName = string.Format("{0} {1}", person.FirstName, person.LastName);
            person.PersonId = int.Parse(controllerContext.HttpContext.Request.Form["PersonId"]);
            return person;
        }
    }

Use Custom Model Binder:  We can use custom model binder by applying attribute on model or by registering globally using “Global.asax” file.

ModelBinder Attribute : Way of registering a custom model binder is to apply the ModelBinder attribute to the model.

Example:
[ModelBinder(typeof(PersonBinder))]
    public class Person
    {
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sex { get; set; }

        [HiddenInput(DisplayValue = false)]
        public string FullName { get; set; }
    }


Assigning model binders in Global.asax: We register our binder through the ModelBinders.Binders.Add method, passing in the type that our binder supports and an instance of the binder class. We can do that in the Application_Start event inside the Global.asax.

ModelBinders.Binders.Add(typeof(Person), new PersonBinder());

10 comments:

  1. Thanks for updating new information about hhtml. It helped me a lot to improve my businesses. Practically as a developer you have shared lot of details about html. Also share your new updated details about html. Thanks mate.
    Web Designing training

    ReplyDelete

  2. Hey, nice site you have here! Keep up the excellent work!



    Dot Net Training in Chennai

    ReplyDelete
  3. Thanks for giving important information to training seekers,Keep posting useful information..

    DOT NET Training Chennai

    ReplyDelete
  4. Thanks for sharing this useful information..Its really very informative.

    Dot Net Training

    ReplyDelete
  5. Really nice post. SEO is one of the digital marketing techniques used for improve the website ranking in search engine result page. To know more details please call 9003623340.
    Regards..
    SEO Training institute in Chennai

    ReplyDelete
  6. ice post. PHP is one of the server side scripting language mainly used for designing website. So learning PHP Training in Chennai is really useful to make a better career.
    Regards..
    HTML5 Training in Chennai

    ReplyDelete
  7. Hi, I am Victoria from Chennai. I am technology freak. I did Hadoop Training in Chennai at FITA. This is useful for me to make a bright career in IT field.

    ReplyDelete
  8. Your information about asp is really interesting and innovative. Also I want you to share latest updates about asp. Can you update it in your website? Thanks for sharing. It is integrated on MS Windows server to facilitate


    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery




    ReplyDelete