ASP. net mvc DefaultModelBinder,

Source: Internet
Author: User
Tags tojson

ASP. net mvc DefaultModelBinder,

Reprinted from

Leo's Blog

 

Many ASP. net mvc projects are still retrieving data from request. querystring or formContext. Some projects have built a large number of custom modelbinder, which is very good and actually lags behind.

 

ASP. net mvc provides the default Implementation of IModelBinder. This implementation class is called defamodelmodelbinder. When writing code, we almost cannot feel the existence of this class, because this class automatically parses the request information into the action parameter. This article will show you how powerful this class can save a lot of code.

 

Let's look at an example. The following table is used to edit the user information and the user's schedule. In this example, I will use defamodelmodelbinder to automatically parse the entire form data into an instance of a complex entity class. No lines of manually parsed C # code need to be written.

 

 

The corresponding controller code is as follows:

 1 public class DemoController : PublicControllerBase 2 { 3     public ActionResult UserEditor() 4     { 5         return View(); 6     } 7  8     [HttpPost] 9     public string SaveUser(DemoUser user)10     {11         var result = string.Empty;12         if (user != null)13         {14             result = Serializer.ToJson(user);15         }16         return result;17     }18 }

 

The definition of related object classes is also very simple:

public class DemoUser{    public string Username { get; set; }    public string Email { get; set; }    public string Language { get; set; }    public Gender Gender { get; set; }    public int[] RoleIds { get; set; }    public List<ScheduledJob> Jobs { get; set; } }public class ScheduledJob{    public string Job { get; set; }    public string From { get; set; }    public string To { get; set; }}public enum Gender{    Unknown = 0,    Male = 1,    Female = 2}

 

Note that the parameter SaveUser is an object of a complex entity class. DefaultModelBinder automatically parses the complex form. The saved action directly serializes the JSON string of the parameter user and returns it to the browser.

 

Let's take a look at HTML and JS.

 

HTML:

1 <form id = "formUserEditor" action = "/demo/saveuser" method = "POST"> 2 <table class = "form"> 3 <colgroup> 4 <col width = "100"/> 5 <col width = "auto"/> 6 </colgroup> 7 <tbody> 8 <tr> 9 <td> User Name: </td> 10 <td> 11 <input id = "txtUsername" type = "text" name = "username"/> 12 </td> 13 </tr> 14 <tr> 15 <td> Email: </td> 16 <td> 17 <input id = "txtEmail" type = "text" name = "email"/> 18 </td> 19 </tr> 20 <tr> 21 <td> language: </td> 22 <td> 23 <select id = "ddlages" name = "language"> 24 <option value = "zh-cn"> Chinese </option> 25 <option value = "en-us"> English </option> 26 </select> 27 </td> 28 </tr> 29 <tr> 30 <td> gender: </td> 31 <td id = "genders"> 32 <input type = "radio" name = "gender" value = "@ (Taoad. web. publics. controllers. gender. unknown) "id =" rdUnknown "/> 33 <label for =" rdUnknown "> unknown </label> 34 35 <input type =" radio "name =" gender "value = "@ (Taoad. web. publics. controllers. gender. male) "id =" rdMale "/> 36 <label for =" rdMale "> male </label> 37 38 <input type =" radio "name =" gender "value = "@ (Taoad. web. publics. controllers. gender. female) "id =" rdFemale "/> 39 <label for =" rdFemale "> female </label> 40 </td> 41 </tr> 42 <tr> 43 <td> role: </td> 44 <td id = "roles"> 45 <input type = "checkbox" name = "roleids" value = "1" id = "cb1"/> 46 <label for = "cb1"> administrator </label> 47 48 <input type = "checkbox" name = "roleids" value = "2" id = "cb2"/> 49 <label for = "cb2"> department manager </label> 50 51 <input type = "checkbox" name = "roleids" value = "3" id = "cb3"/> 52 <label for = "cb3"> customer </label> 53 </td> 54 </tr> 55 <tr> 56 <td> time: </td> 57 <td> 58 <ul id = "jobs"> 59 60 </ul> 61 <input type = "button" value = "add" id = "btnAddJob "/> 62 </td> 63 </tr> 64 <tr> 65 <td> </td> 66 <td> 67 <input type =" button "value =" save "id =" btnSave "/> 68 <input type =" button "value =" cancel "id =" btnCancel "/> 69 </td> 70 </tr> 71 </tbody> 72 </table> 73 </form> 74 

 

JS:

1 <script language = "javascript" type = "text/javascript"> 2 $ (document ). ready (function () {3 $ ("# btnAddJob "). click (function () {4 var $ newLi = $ (html); 5 $ ("# jobs "). append ($ newLi); 6 bindLi ($ newLi); 7}); 8 9 $ ("# btnSave "). click (function () {10 var data =$ ("# formUserEditor "). serialize (); 11 $ ("# jobs li "). each (function (I) {12 var prefix = "& jobs [" + I + "]"; 13 data + = prefix + ". job = "+ $ (this ). find (". job-id "). val (); 14 data + = prefix + ". from = "+ $ (this ). find (". job-from "). val (); 15 data + = prefix + ". to = "+ $ (this ). find (". job-"). val (); 16}); 17 demo. ajax. post ("/demo/saveuser", data, function (json) {18 $ ("# json" ).html (json); 19}); 20}); 21 }); 22 23 function bindLi (li) {24 $ (li ). find (". btn-add "). click (function () {25 var $ li = $ (this ). closest ("li"); 26 var $ newLi = $ (html); 27 $ li. after ($ newLi); 28 bindLi ($ newLi); 29}); 30 $ (li ). find (". btn-delete "). click (function () {31 $ (this ). closest ("li "). remove (); 32 }); 33} 34 35 var html = '<li> \ 36 <select class = "job-id"> \ 37 <option value = "job1"> Work 1 </option> \ 38 <option value = "job2"> job 2 </option> \ 39 </select> \ 40 <input type = "text" placeholder = "Start Time" class = "job -from "/> \ 41 ---- \ 42 <input type =" text "placeholder =" End Time "class =" job-to "/> \ 43 <a href =" javascript: void (0); "class =" btn-add "> add </a> | \ 44 <a href =" javascript: void (0 ); "class =" btn-delete "> delete </a> \ 45 </li> '; 46 </script>

 

For the following table data:

 

After you click Save, the returned JSON data is:

 

We can see that all the form data is successfully saved.

 

Let's look at the request information:

 

Note the value of content-type.

 

In fact, the form data from POST to the server is just a string, as shown below:

 

Copy the following string:

Ajax = true & username = leo & email = leo % 40gmail.com & language = zh-cn & gender = Unknown & roleids = 1 & roleids = 3 & jobs [0]. job = job1 & jobs [0]. from = 9:00 & jobs [0]. to = 10: 00 & jobs [1]. job = job2 & jobs [1]. from = 10: 00 & jobs [1]. to = 11: 00

 

We can see that javascript can be used to concatenate a string, serialize the entire form into a string in the form of a key-value pair, and then upload the string to the server. Then defamodelbinder can automatically parse the object class.

 

The key point is to add an array subscript to List or array-type data. In this way, DefaultModelBinder can automatically parse any complicated data structure.

 

Thought 1:

If the keys of form data are prefixed with "deoffset", as shown below, can the parameters of this action be automatically parsed?

Demicro. username = leo & demicro. email = leo@gmail.com & demouser.jobs [0]. job = job1 &.....

 

The Action is as follows:

 1 [HttpPost] 2 public string SaveUser(DemoUser user) 3 { 4     var result = string.Empty; 5     if (user != null) 6     { 7         result = Serializer.ToJson(user); 8     } 9     return result;10 }

 

What if the parameter name of the action is changed to deoffset?

 

Thinking 2:

If you change the parameter name of the action to the following code, can the parameter be automatically parsed? (Form data is not prefixed with "deoffset)

Ajax = true & username = leo & email = leo % 40gmail.com & language = zh-cn & gender = Unknown & roleids = 1 & roleids = 3 & jobs [0]. job = job1 & jobs [0]. from = 9:00 & jobs [0]. to = 10: 00 & jobs [1]. job = job2 & jobs [1]. from = 10: 00 & jobs [1]. to = 11: 00

 

The Action is as follows:

 1 [HttpPost] 2 public string SaveUser(DemoUser demoUser) 3 { 4     var result = string.Empty; 5     if (demoUser != null) 6     { 7         result = Serializer.ToJson(demoUser); 8     } 9     return result;10 }

 

Think 3:

If the parameter of action is wrapped in another class, as shown in the following code, what string should form data be so that DefaultModelBinder can be automatically parsed?

 1 public class UserEditorViewModel 2 { 3     public DemoUser DemoUser { get; set; } 4 } 5  6 [HttpPost] 7 public string SaveUser(UserEditorViewModel model) 8 { 9     var result = string.Empty;10     if (model != null)11     {12         result = Serializer.ToJson(model);13     }14     return result;15 }

 

Thinking 4:

If action is defined in this way, how can we combine the strings of form data?

 1 [HttpPost] 2 public string SaveUser(DemoUser demoUser, List<ScheduledJob> scheduledJobs) 3 { 4     var result = string.Empty; 5     if (demoUser != null) 6     { 7         demoUser.Jobs = scheduledJobs; 8         result = Serializer.ToJson(demoUser); 9     }10     return result;11 }

 


What is aspnet mvc?

The MVC Architecture is short for "Model-View-Controller". The Chinese translation is "Model-View-Controller ".
The encyclopedia already has a good description.
Baike.baidu.com/view/739359.htm? Fr = ala0_1_1

ASP. NET models can also be divided into BLL-> DAL
What LZ said is that ASP. net mvc is not JAVA. Everyone knows that asp.net is mainly based on the event-driven mechanism.
However, this mechanism has many disadvantages, such as slow running speed (relatively), and has to input various technologies (such as AJAX) ASP to control refreshing. net mvc, in Microsoft's words, is to discard the event mechanism and discard the runat = "server" control. In short, there are different opinions. NET professionals can proudly say in front of JAVA: "Our MVC performance is better than JAVA! "

I wrote a little slowly. Haha, someone has posted a large film.

Edu.codepub.com/2009/0422/3206.php
Next, I will post a Quick Start for LZ. For more details, and try asp.net without aspx. cs: D.

Aspnet mvc

You can configure multiple database connections through web. config.
<Deleetask>
<Add key = "ConnectionString" value = "Data Source = (local); Database = data; Uid = sa; PWD = 123"/>
<Add key = "ConnectionString1" value = "Data Source = 192.168.1.1, Database = data1, Uid = sa, PWD = 123"/>
<Add key = "ConnectionString2" value = "Data Source = 192.168.1.2; Database = data2; Uid = sa; PWD = 123"/>
<Add key = "ConnectionString3" value = "Data Source = 192.168.1.3; Database = data3; Uid = sa; PWD = 123"/>
</AppSettings>

When logging on, use session to record the selected company data source
Database Connection statement:
SqlConnection sqlconn = null;
If (Session ["data"] = "01 ")
Sqlconn = new SqlConnection (ConfigurationManager. etettings ["ConnectionString"]);
Else if (Session ["data"] = "02 ")
Sqlconn = new SqlConnection (ConfigurationManager. etettings ["ConnectionString1"]);
Else if (Session ["data"] = "03 ")
Sqlconn = new SqlConnection (ConfigurationManager. etettings ["ConnectionString2"]);
Else if (Session ["data"] = "04 ")
Sqlconn = new SqlConnection (ConfigurationManager. etettings ["ConnectionString3"]);

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.