[Asp.net mvc odd tricks] 04, asp. netmvc04

Source: Internet
Author: User

[Asp.net mvc odd tricks] 04, asp. netmvc04

In the QQ group or some program communication platforms, some people often ask: IHow to send an array to receive it in Action, MeWhy does the Action model fail to receive the passed array?Or meSome arrays are set in ajax data. why can't the backend receive them?And some otherHow to transmit a complex objectOrHow does Action receive a complex object?And so on. Or some people may encounter complicated objects or arrays to directly transmit a json string, and then convert the json string into a model object in the Action. Of course, this is also an approach, but it may not be the best practice.

 

I. Requirements

Input to Action according to the data format and receive it using a UserInfo Model. The requirement is very simple.

After analysis, we can see that the hobby is an array of strings. The user contains a company object, and the company object contains a telephone array. The user also contains an array object, so our Model should be:

public class UserInfo{    public string Name { get; set; }    public int Age { get; set; }    public string[] Bobbys { get; set; }    public Company Company { get; set; }    public Star[] Star { get; set; }}public class Company{    public string Name { get; set; }    public string Address { get; set; }    public string[] Tel { get; set; }}public class Star{    public string Name { get; set; }    public int Age { get; set; }    public string Movie { get; set; }}

 

Ii. Form submission literacy and Verification

When submitting a form, whether it is post or get, most of the data we submit isKey-value pairsJson object is not directly imported to the background, but only json objects of strings can be imported at most. This may be caused by incorrect ajax data settings, many people may think that json objects can be directly set and submitted to the background. A simple Model may receive json objects, but it is a little complicated, such as those containing arrays, even if the json format is the same as the Model format, the Model does not receive the array data submitted at the front end. This is also a problem I raised at the beginning of this article.

In order to verify the ajax data submitted in json format, let's verify it.

Action:

[HttpPost]public ActionResult Index(UserInfo user){    return Json(user);}

Ajax:

$. Ajax ({url: "/", type: "post", data:{"Name": "Emrys", "age": "26", "bobbys": ["football", "movie"], "company": {"name ": "Shanghai xxxxxx Company", "address": "xxxx Road, Xuhui District, Shanghai", "tel": ["021-88888881", "021-88888882", "021-88888883 ", "021-88888884"]}, "star": [{"name": "Jackie Chan", "age": "63", "movie": "12 Zodiac "}, {"name": "Liu Yifei", "age": "18", "movie": "King of Kung Fu" },{ "name": "Hu ge", "age ": "24", "movie": "ranklist"}]}, Success: function (r) {console. log (r );}});

This is the data format that we often submit. If the model format in the background is the same as the data format, only one name can receive data normally, all other data will not be received. Let's take a look at the format of the key-Value Pair converted by jquery. We can see the submitted format from the network of chrome or Firefox debugging tool.

The array format is: xxxxxx [], and the object format in the object is xxxx [yyyyy]. I have not explored why this format is used, the format may be required for other languages, such as php, jsp, or other languages. However, asp.net mvc obviously does not need this format.

The next part is the verification that ruined the three views. All the results can use the Model to receive, and I ......... Suddenly I felt like there were one hundred people flying over ..........

I once doubted myself. Was it wrong to understand the model binding I had developed through mvc for a few years? I could not receive data when I used jquery ajax to convert it into a format, why. After exploration and testing, I found that I had not understood the error before. It turned out to beVersion. I tested mvc5,Mvc5 may have optimized the format converted from jquery ajax,Versions earlier than mvc5 are not allowed. This is the focus.

That is to say, if you use mvc5 for development, it is much simpler. You can directly set json-format data in ajax data, which is complex and can be used as an array, maybe Microsoft developers also discovered this problem and solved it in mvc5. I didn't study the differences between source code. In short, mvc5 is acceptable. The previous version of mvc5 will encounter the problem I mentioned.

 

Iii. Model binding Analysis

A blog simulated form can already contain most of the form formats encountered during website development, including arrays and objects.

Some model binding rules have been found in the previously developed mvc project. The difference lies in the objects in arrays and objects.

The following figure shows the values that are manually converted to key-value pairs,Versions earlier than mvc5Applicable format. Of course, mvc5 is also recognizable, or this format is applicable to all mvc versions.

Is a comparison chart of two formats

 

Let's summarize the Rules. It should be very simple.

Someone may ask how to spell the format manually. Here, two formats are often used.

1. Directly concatenate strings
$. Ajax ({url: "/", type: "post", data: "name = Emrys & age = 26 & bobbys [0] = soccer & star [0]. movie = freeloaders ", success: function (r) {console. log (r );}});

 

2. javascript objects
Var data1 = {name: "Emrys"}; data1.age = 26; data1 ["bobbys [0]"] = ""; data1 ["star [0]. movie "] =" ranklist "; $. ajax ({url: "/", type: "post", data: data1, success: function (r) {console. log ("xxxxxxxxxxxxxx"); console. log (r );}});

You can select different splicing methods as needed.

 

Iv. Summary

By the way, I would like to share my tips. When we get a piece of json, don't rush to create a model in the class, one by one, vs already provides a powerful tool. You can ignore this section if you know it.

 

Source Address Github: https://github.com/Emrys5/Asp.MVC-04-ModelBinding

The above are some of the applications related to model binding. This article is original. You are welcome to make a brick andRecommendation.

Series courses
  • [Asp.net mvc odd tricks] 01-encapsulation context-Get custom context in View
  • [Asp.net mvc odd tricks] 02-use the Razor engine to generate Html code in the Action
  • [Asp.net mvc odd tricks] 03-enumeration feature extensions solve enumeration naming problems and support HtmlHelper
  • [Asp.net mvc odd tricks] 04-Do you actually use the Action model to bind it?

 

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.