MVC model binding and mvc model binding

Source: Internet
Author: User
Tags try catch

MVC model binding and mvc model binding
MVC model binding

In WebForm, the value of the submitted Form is generally obtained in the Form of Request. Form ["Title. The model binding mechanism is provided in MVC. It makes it easier to obtain parameters in a form or Url in the background.

I. Basic Model binding

You can directly use a string, integer variable, entity, or List <entity> In the parameter to obtain the parameters submitted by the form.

The parameters all correspond to the name attribute of the Html control in the form.

        public ActionResult PersonAdd(int Id)        {            return View();        }

For example, the above code matches the Id parameter in the Url. For example, the IDs of the following two methods can be matched to 1.

  http://localhost/Home/PersonAdd/1  http://localhost/Home/PersonAdd?Id=1

The following code is used:

        public ActionResult PersonAdd(string Name)        {            return View();        }

It can match the three parts submitted in the form:

<Input type = "text" name = "Name" value = "Zhang San"/>

It can also match the path parameters of the Get request:

Http: // localhost/Home/PersonAdd? Name = James

If an object is used, the attribute name of the object is checked for the value of the tag corresponding to the name attribute in the form.

For example, there are the following entities:

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

Enter the following parameters in Controller:

[HttpPost] public ActionResult PersonAdd (Person_Model model) {if (ModelState. isValid) // This is only for demonstration. Security is not considered. {// return Redirect ("/Home/PersonManager") is omitted when you insert a database;} return View ();}

In this way, the model binder will automatically check and bind the tags corresponding to the attributes of the object and their names. The values of the following form will be bound to the attributes of the model object.

<Input type = "hidden" name = "Id" value = "1"/> <input type = "text" name = "Name" value = "Zhang San"/>
Ii. explicit model binding

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

UpdateModel throws an exception. Therefore, UpdateModel should be packaged with try catch statement blocks. Instead of throwing an exception, TryUpdateModel returns a Boolean value. true indicates that the binding is successful, and false indicates that the binding fails. For example:

[HttpPost] public ActionResult PersonAdd () {Person_Model model = new Person_Model (); try {UpdateModel (model); // Insert the database return Redirect ("/Home/PersonManager ");} catch {return View (model );}}

TruUpdateModel:

[HttpPost] public ActionResult PersonAdd () {Person_Model model = new Person_Model (); if (TryUpdateModel (model )) {// Insert the database return Redirect ("/Home/PersonManager");} else {return View (model );}}

In addition, the model binding has a model State. Each value in the model of the model binder is recorded in the model state. You can view the binding status at any time. For example:

[HttpPost] public ActionResult PersonAdd () {Person_Model model = new Person_Model (); TryUpdateModel (model); if (ModelState. isValid) {// if (ModelState. isValidField ("Name") // Insert the database return Redirect ("/Home/PersonManager");} else {return View (model );}}
Iii. Security Questions: repeated submission

Suppose there are the following entities:

Public class Comment {public int Id {get; set;} // comments Name public string Name {get; set;} // comments public string Content {get; set ;} // whether public bool Approved {get; set ;}} has been reviewed ;}}

In Controller:

Public ActionResult CommentAdd (Comment com) {if (ModelState. isValid) {// Add the 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 Form submission, the comment will pass the review by default. In this case, we can use the Bind feature to defend against repeated commit attacks.

Whitelist:

[Bind (Include = "Name, Content")] // whitelist, Bind only the two attributes [Bind (Exclude = "Id, Approved")] // blacklist, do not bind these two attributes

The Bind feature can be applied to the left side of the parameter or the top of the object Model class. The feature applies to the top of the entity Modle to Bind all objects, the application on the left side of the parameter is only valid for the request in the action.

For example:

Public ActionResult CommentAdd ([Bind (Exclude = "Approved")] Comment com) {if (ModelState. isValid) {// Add the database return Redirect ("/Home/CommentManager");} else {return View (com );}}

In addition, UpdateModel and TryUpdateModel also have an overloaded version to receive a binding list:

UpdateModel(com, "", new string[] { "Id", "Name", "Content" });

Finally, there is also a view model, that is, defining a model for the view to use only the attributes to be bound.

  In addition, if two classes have the same Name attribute, they must be bound at the same time. To distinguish between HTML classes, you can write as follows:

<P> customer name: <input type = "text" Name = "customer. name"> public interface IModelBinder {object BindModel (ControllerContext controllerContext, ModelBindContext bindingContext );}

  1. Bind a Model

By default, ASP. net mvc uses defamodelmodelbinder to bind Model data. When the Action parameter is passed, ASP. net mvc searches for matched data in the following order:

  2. Simple parameters and complex parameters

If the parameter type of the Action method is value type and string type, defamodelmodelbinder searches for parameters that match the Action parameter name. If no corresponding parameter exists, then the parameter of Action will try to assign a null reference. Therefore, for simple type parameters, the parameter type should be null.

In most cases, a Model object is used to process complex parameters. defamodelmodelbinder traverses the attributes of the Model object to bind parameters.
If you do not want defamodelmodelbinder to bind a parameter, you can describe it using BindAttribute, which defines three attributes:

  • Include indicates the attributes to be bound. Each attribute is separated by a comma.
  • Exclude indicates the attributes that do not need to be bound. Each attribute is separated by commas.
  • Prefix indicates the Prefix of the request parameter.

  These labels can be defined on the Model.The attribute to be bound or not to be bound during parameter binding, for example:

[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 and excluded attributes.

UpdateModel(  person,     //Model  "person",    //Prefix  new[] { "Id","Name" },  //Include  new [] { "Birthday" }   //Exclude);

 

Related Article

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.