MVC Model Binding

Source: Internet
Author: User
Tags try catch

In WebForm, getting the value of the submitted form is generally the way of request.form["Title". In MVC, the model binding mechanism is provided. It's easier to get the parameters in the form or URL in the background.

First, the basic model binding

You can get the parameters of a form submission directly in a parameter using a string, integer variable, entity, or list< entity >.

These things in the parameters correspond to the Name property one by one of the HTML control in the form.

        Public ActionResult personadd (int Id)        {            return View ();        }

For example, the above code can match the ID parameter in the URL. The following two method IDs can be matched to 1

HTTP://LOCALHOST/HOME/PERSONADD/1 http://localhost/Home/PersonAdd?Id=1

In code such as the following:

        Public ActionResult Personadd (string Name)        {            return View ();        }

It can match the Zhang San submitted in the form:

<input type= "text" name= "name" value= "Zhang San"/>

You can also match the path parameters to the GET request:

Http://localhost/Home/PersonAdd?Name= Zhang San

If the entity is used, the attribute name of the entity is checked against the value of the label in the Name property in the form.

For example, there are the following entities:

    public class Person_model    {public        int Id {get; set;}        public string Name {get; set;}    }

The parameters in the controller are filled in as follows:

        [HttpPost]        Public ActionResult Personadd (Person_model Model)        {            if (modelstate.isvalid)//Here for demonstration only, regardless of security            {                // Insert Database Omit                return Redirect ("/home/personmanager");            }            return View ();        }

In this case, the model binder automatically checks the properties of the entity against the label of the name one by one and binds it. The values of the following form will be bound to the properties of the model entity.

<input type= "hidden" name= "Id" value= "1"/> <input type= "text" name= "name" value= "Zhang San"/>
Second, explicit model binding

Both Updatemodel and TryUpdateModel are used to display model bindings. If an error occurs during binding or the model is invalid.

Updatemodel will throw an exception. So Updatemodel is wrapped with a try catch statement block, and TryUpdateModel does not throw an exception, but instead returns a Boolean type value, True to indicate that the binding was successful, and false to indicate that the binding failed. Such as:

        [HttpPost]        Public ActionResult Personadd ()        {            Person_model Model = new Person_model ();            Try            {                Updatemodel (model);                Insert Database                return Redirect ("/home/personmanager");            }            Catch            {                return View (model);            }        }

Truupdatemodel:

        [HttpPost]        Public ActionResult Personadd ()        {            Person_model Model = new Person_model ();            if (TryUpdateModel (model))            {                //Insert Database                return Redirect ("/home/personmanager");            }            else            {                return View (model);            }        }

In addition, model bindings also have a model state, and model binders each value in the model has a corresponding record in the model state. You can view the binding status at any time. Such as:

        [HttpPost]        Public ActionResult Personadd ()        {            Person_model Model = new Person_model ();            TryUpdateModel (model);            if (modelstate.isvalid)            {                //if (Modelstate.isvalidfield ("Name"))                //Insert Database                return Redirect ("/home/ Personmanager ");            }            else            {                return View (model);            }        }
III. Security issues: Duplicate Submissions

Suppose you have the following entities:

    public class Comment    {public        int Id {get; set;}        Reviewer name public        string name {get; set;}        Comment Public        string content {get; set;}        Whether public        BOOL approved {get; set;}} has been audited    

In the controller:

        Public actionresult Commentadd (Comment com)        {            if (modelstate.isvalid)            {                //Add database                return Redirect ("/home/commentmanager");            }            else            {                 return View (COM);            }        }

In the above code, if a malicious user adds "approved=true" to the form data to intervene in the form's submission, the comment will be approved by default. At this point we can use the bind feature to defend against repeated commit attacks.

White list:

[Bind (include= "Name,content")]   Whitelist, bind only these two properties [Bind (exclude= "id,approved")]        //blacklist, do not bind these two properties

The bind attribute can be applied to the left of the parameter or to the top of the entity model class, the top of the entity Modle is valid for all the entity bindings, and to the left of the parameter is only valid for the request in the action.

Such as:

Public ActionResult Commentadd ([Bind (exclude= "approved")]comment com) {if (modelstate.isvalid) {//Add database Retu   RN Redirect ("/home/commentmanager");   } else {return View (COM); } }

In addition, Updatemodel and TryUpdateModel also have an overloaded version to receive a list of bindings:

Updatemodel (COM, "", new string[] {"Id", "Name", "Content"});

Finally, there is the view model, in addition to defining a model to be used exclusively for the view, including only the attributes that need to be bound.

  In addition, if two classes have the same name attribute, to bind at the same time, the distinguished HTML can be written like this:

<p> Customer Name: <input type= "text" Name= "customer. Name "style=" width:300px "/></p><p> Salesperson: <input type=" text "Name=" salesman. Name "style=" width:300px "/></p>

Third, the model binding principle

in ASP. NET MVC, the user requests that the data of the server be packaged as a model data object, which is usually also used by view to provide the displayed data. in ASP. NET MVC, a very flexible model binding mechanism is provided, which defines the contract for binding model data and provides the default implementation Defaultmodelbinder of an interface through the Imodelbinder excuse. In most cases, the model binding can be done just by Defaultmodelbinder.

If necessary, you can also customize a Imodelbinder implementation to complete a specific type of model binding.

Public interface imodelbinder{    Object Bindmodel (ControllerContext controllercontext,modelbindcontext BindingContext);}

  1. Binding model

By default, ASP. NET MVC uses Defaultmodelbinder to bind the model's data. When you pass the action parameter, ASP. NET MVC looks for matching data in the following order:

    1. The data in the form form;
    2. Data in the Routedata;
    3. Data in the QueryString;

  2. Simple parameters and complex parameters

If the argument type of the action method is a value type and a string type, then Defaultmodelbinder will look for the parameter that matches the action parameter name, and if there is no corresponding argument, then the action argument will attempt to give the null reference. Therefore, for a simple type parameter, the type of the parameter should be nullable.

In most cases, we will handle complex parameters through a model object, and Defaultmodelbinder will iterate through the properties of the model object to bind the parameters.
If you do not want Defaultmodelbinder to bind a parameter, you can describe it through Bindattribute, which defines three properties:

    • The include represents a property that needs to be bound, separated by commas between the attributes.
    • Exclude represents a property that does not need to be bound, and each property is separated by commas.
    • Prefix represents the prefix of the request parameter.

  These tags can be defined on the model, explaining the properties that need to be bound during parameter binding, or properties that do not require binding, such as:

[Bind (Include = "Name,birthday")]public class person{public int Id {get; set;}  public string Name {get; set;} Public DateTime birthday{get; set;}}

In the Updatemodel method, specify the contained property and the property that is not included.

Updatemodel (person,     //model ' person ',    //prefix new[] {"Id", "Name"},//include new [] {"Birthday"}//ex Clude);

MVC Model Binding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.