ASP. NET MVC Learning Model bindings (1)

Source: Internet
Author: User

I. Preface

Below we will begin to learn about model binding, through which we will be able to understand how the model binder of the ASP. NET MVC model transforms the data in the HTTP request into a model, where we focus on the form data.

Two. Text

1. Simple Type Binding

learned that an ASP . Net-MVC would be proud of this feature, which is the ability to map a form with a parameter of the same name, which is a lot lighter than manipulating the ASP to get the value, but as mentioned above, the same name (case insensitive ), we'll tell you how to specify it yourself.

First we get the values in the form in HomeController( created if it doesn't exist ) and display:

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5 public         ActionResult Inde X () 6         {7             return View (); 8         } 9         [httppost]11 public         ActionResult Index (String person) 12         {             tempdata["msg"] = person?? ""; "             return View ();         }16     }17}

We then write the following code in views/home/index.cshtml :

1 @{2     viewbag.title = "Index"; 3} 4  5 @using (Html.BeginForm ()) 6 {7     <input type= "text" name= "person"/& Gt 8     <input type= "Submit" value= "Submit"/> 9}10 @if (Tempdata.containskey ("MSG")) {<p>14         @TempData ["MSG"]. ToString ()     </p>16}

Here we have an input box named person, the following we also output this value after submission. Below the reader can try to enter a value, you can see the corresponding output below. But this time we will change the name of the person input box to persons will not be displayed. The reason is simple, because the name is different, but with the Bind annotation attribute can solve this problem, let's open HomeController and modify the code:

1 [httppost]2 Public ActionResult Index ([Bind (prefix= ' persons ')]string person) 3 {4 tempdata["msg"] = person?? ""; 5 return View (); 6}

Here we change the prefix of person with Bind 's Prefix , and then recompile, we can find and display again. Then we don't need the same name.

The above is only for a simple type of case, of course, more can be and so on, but if it is an array? Thanks to the default model bindings for ASP . We just repeat the same name multiple times, we can simply form an array, for example, we will change the index.cshtml to the following code:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" name= "persons"/> 4     <input type= "text" name= "person S "/> 5     <input type=" text "name=" persons "/> 6     <input type=" text "name=" persons "/> 7     < Input type= "text" name= "persons"/> 8     <input type= "text" name= "persons"/> 9     <input type= "Submit" Value= "Submit"/>10}11 @if (Tempdata.containskey ("MSG")) and     <p>15         @TempData ["MSG"]. ToString ()     </p>17}

As a demonstration we simply copied the input box several times, and below we modify the HomeController code:

1 [httppost]2 Public ActionResult Index ([Bind (prefix= ' persons ')]ilist<string> person) 3 {4 tempdata["msg"] = String.Join (";", person); 5 return View (); 6}

With the above code we can see that the Bind annotation attribute can be used even if the array is the same, and the type is changed to ilist<string>. The Join method joins the array into an array, separated by semicolons. The reader can recompile and try this time, and the final effect is as follows:

2. Composite type Binding

There are a lot of practical situations where we use a compound type instead of multiple simple types, so the question is, how does ASP. NETMVC bind? For a composite type, the corresponding property in the composite attribute will be mapped by name, but the curious person will definitely use the Bind annotation attribute and want to see what happens, so let's simulate it below, first we create a simple person class :

1 namespace Mvcstudy.models2 {3 public     class Person4     {5 public         String FirstName {get; set;} 6 Public         String LastName {get; set;} 7 public         Address homeaddress {get; set;} 8     }9}

There is also an Address class (which needs to be used later ):

1 namespace Mvcstudy.models2 {3 public     class ADDRESS4     {5 public         String Line1 {get; set;} 6 Public         String Line2 {get; set;} 7     }8}

We then modify the index.cshtml to correspond the input boxes of the form to the person:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" name= "FirstName"/> 4     <input type= "text" Name= "La Stname "/> 5     <input type=" Submit "value=" Submit "/> 6} 7  8 @if (Tempdata.containskey (" MSG ")) 9 {10
   <p>11         @TempData ["MSG"]. ToString ()     </p>13}

Also, modify the code in the homecontroller :

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5 public         ActionResult Inde X () 6         {7             return View (); 8         } 9         [httppost]11 public         actionresult Index (person person)         {13< c9/>tempdata["msg"] = person. FirstName + person. Lastname;14             return View ();         }16     }17}

Before we use the bind annotation property, we can see that the final output is correct, and then we add the bind annotation property:

1 [httppost]2 Public ActionResult Index ([Bind (prefix= "P")]person person) 3 {4 tempdata["msg"] = person. FirstName + person. Lastname;5 return View (); 6}

Recompile, we can see that we will not output our expected results at the end, and the also reported is abnormal. This time we consider what this Prefix is doing here, literally the meaning of the prefix, but we find that in a simple type it is simply that the simple type will be taken from the form's Key to the specified value. But here is the class, so the meaning is different, instead of adding a pto all the properties in the class and appending a point later. Here we modify the index.cshtml code:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" name= "P.firstname"/> 4     <input type= "text" Name= "p. LastName "/> 5     <input type=" Submit "value=" Submit "/> 6} 7  8 @if (Tempdata.containskey (" MSG ")) 9 {10
   
    <p>11         @TempData ["MSG"]. ToString ()     </p>13}
   

Then we refresh the page, re-test, we can find the value and output. But we can see that there is also a homeaddress property in this class, but this property is an Address class, How is this name represented? You might think of the name of the attribute in Address , but that's not the case, because instead of dividing it through points as above, we modify the index.cshtml code as follows:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" name= "P.firstname"/> 4     <input type= "text" Name= "p. LastName "/> 5     <input type=" text "name=" P.homeaddress.line1 "/> 6     <input type=" text "Name=" p. Homeaddress.line2 "/> 7     <input type=" Submit "value=" Submit "/> 8} 9 @if (Tempdata.containskey (" MSG ")) 11 {     <p>13         @TempData ["MSG"]. ToString ()     </p>15}

Above we see we pass the homeaddress of person to ASP. NET MVC through p.homeaddress.line1 Of course we have to modify HomeController or not see the final effect:

1 [httppost]2 Public ActionResult Index ([Bind (prefix= "P")]person person) 3 {4 tempdata["msg"] = person. Homeaddress.line1 + person. Homeaddress.line2;5 return View (); 6}

Finally we can test, we must all see the output bar. Even if the class, there will be an array of circumstances, then how do we? Of course, the use of this point to split, but the front is not the name but the index value, the following we certainly want to modify index.cshtml:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" Name= "[0]. FirstName "/> 4     <input type=" text "Name=" [0]. LastName "/> 5     <input type=" text "Name=" [1]. FirstName "/> 6     <input type=" text "Name=" [1]. LastName "/> 7     <input type=" Submit "value=" Submit "/> 8} 9 @if (Tempdata.containskey (" MSG ")) one by one {     &L t;p>13         @TempData ["MSG"]. ToString ()     </p>15}

Here we use [] as the first delimiter, the value is the index value, the following we also want to modify HomeController, so as to output the result:

1 [httppost]2 Public actionresult Index (list<person> person) 3 {4 tempdata["msg"] = person. Count.tostring (); 5 return View (); 6}

To make it easier to output only the number of items, and then we recompile, refresh the page to see that the output is always 2, no matter what you enter the value, because http will send the four input boxes to the server. If you are using JS dynamic generation, then the trouble is that you are responsible for maintaining these indexes, fortunately, ASP . NET MVC think of this, so also provides another solution, we can put the above index.cshtml change to the following code:

1 @using (Html.BeginForm ()) 2 {3     <input type= "hidden" name= "index" value= "first"/> 4     <input type= "text "Name=" [first]. FirstName "/> 5     <input type=" text "Name=" [first]. LastName "/> 6     <input type=" hidden "name=" index "value=" ASD "/> 7     <input type=" text "Name=" [ASD]. FirstName "/> 8     <input type=" text "Name=" [ASD]. LastName "/> 9     <input type=" Submit "value=" Submit "/>10}11 @if (Tempdata.containskey (" MSG "))     <p>15         @TempData ["MSG"]. ToString ()     </p>17}

The only difference here is that a form named index is needed to hold the name of the index, so you just have to ensure that the name of the index is not duplicated, but it's too rigid for a more dynamic situation, if you can use a dictionary. Of course, our wishes are the same, we just need to use name for [index value].key save Key, and use name as index value].value Save the value (valuecan be a class ), such as we modify the index.cshtml code:

1 @using (Html.BeginForm ()) 2 {3     <input type= "text" name= "[0].key"/> 4     <input type= "text" Name= "[0]. Value "/> 5     <input type=" text "name=" [1].key "/> 6     <input type=" text "Name=" [1]. Value "/> 7     <input type=" Submit "value=" Submit "/> 8} 9 @if (Tempdata.containskey (" MSG ")) one by one {     < ;p >13         @TempData ["MSG"]. ToString ()     </p>15}

Then we modify HomeController to receive this dictionary:

1 [httppost]2 Public actionresult Index (dictionary<string,string> person) 3 {4 tempdata["msg"] = string. Join (";", person. Keys); 5 return View (); 6}

Then we recompile and refresh the page, and we can see that the key we entered has been sent out

Transferred from: http://www.cnblogs.com/yaozhenfa/p/asp_net_mvc_model_bind_1.html

ASP. NET MVC Learning Model bindings (1)

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.