Example of model binding using action Tutorial

Source: Internet
Author: User
QQ Group or some of the program Exchange platform, often people ask: I How to send an array to receive in actionI An array of why action is not received in the model, or I in the AJAX data set up some arrays, why the background still can not receive, there are some How to transmit a complex objectOr How the action receives a complex objectWait for these questions. Or some people encounter complex objects or arrays to send a JSON string directly, and then convert the JSON string into the model object in action, which is a practice, but perhaps not the best practice.

First, the demand

According to the data format, incoming to the action, with a userinfo model received, the requirements are very simple.

After analysis we can see that the hobby is an array of strings, the user contains a company object, and then the company object contains a telephone array, the user also contains the 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 validation

When we submit a form, whether it is a post or a get commit, the data we submit is mostly in the form of a key-value pair , and does not pass directly to the JSON object to the background, or to the JSON of only one string, which may be misleading by Ajax data settings, Many people will think that you can directly set the JSON object to submit to the background, perhaps the format of a simple model can be received, but more complex, such as containing the array, etc., even if the JSON format and model format consistent, model does not receive the foreground of the submitted array data, This is also a question that I have just started with the article.

In order to verify what I said about Ajax submitting data in JSON format, we do the verification.

Action:

[Httppost]public actionresult Index (UserInfo user) {return Json (user);}

Ajax:

$.ajax ({    URL: "/",    Type: "POST",    data: {"name": "Emrys",        "age": "+",        "Bobbys": ["Football", "movie"],        "Company": {            "name": "Shanghai XXXXXX Corporation",            "address": "XXXX Road, Xuhui District, Shanghai",            "tel": [                "021-88888881",                " 021-88888882 ",                " 021-88888883 ",                " 021-88888884 "            ]        },        " star ": [            {" Name ":" Dragon "," Age ":" "," "movie": "12 Zodiac"},            {"name": "Liu Yifei", "Age": "+", "movie": "Kung Fu King"},            {"name": "Hu", "Age": "$", "movie": " Langya "}        ]    },    success:function (r) {        Console.log (r);    }});

This is the data format that we often submit, if the model format of our background is identical to the data format, only the name one item can receive the data normally, all other data will not receive, as for why. Let's take a look at the format of the key-value pairs that jquery gives us, and we'll see the submitted format from the network of Chrome or Firefox's debug tool.

Where the format of the array is: xxxxxx[] format, Object format is xxxx[yyyyy] format, I did not explore why this format, perhaps other languages need such a format, php,jsp or other Language bar, but ASP. MVC obviously does not require such a format.

After the destruction of the third view of the verification, the results are all can be used to receive data received, received, received, received, connected, and I ... Suddenly it feels like there are 100 of them flying.

I once doubted that I had done a few years of MVC's development model binding understanding was wrong, before the development of jquery Ajax format is not to receive data ah, that is why AH. After exploring the test found that I did not understand wrong, the original version of the problem. I tested it with the mvc5 done test,MVC5 might have optimized the format of jquery Ajax , but the previous version of MVC5 was not possible, this is the point .

That is to say, if you use the development of the mvc5 do, but a lot simpler, you can directly in the AJAX data set JSON format, complex, array can, perhaps Microsoft developers also found this problem, in mvc5 solved, I did not study the difference between the source, in short, MVC5 is possible. That mvc5 of the previous version would have met the question I said.

Third, model binding analysis

The forms that the blog simulates can already contain most of the form formats that are encountered during the Web development process, including arrays, objects, and so on.

From the previously developed MVC project, some patterns of model binding were found, with the difference between arrays and objects in objects.

The picture below is a manually converted value to a key-value pair, a format that can be applied to aprevious version of Mvc5 , and of course mvc5 is recognizable, or this format is a format that all MVC versions can apply to.

It's a contrast chart of two formats.

As for the rules, it should be easy to sum up.

Some people will ask, how to spell the format of the manual, there are often used in two forms.

1, directly stitching the string

$.ajax ({    URL: "/",    Type: "POST",    data: "name=emrys&age=26&bobbys[0]= football &star[0].movie= Langya List" ,    success:function (r) {        Console.log (r);    }});

2. JavaScript objects

var data1 = {name: "Emrys"};d ata1.age = 26;data1["Bobbys[0]"] = "Football";d ata1["star[0].movie"] = "Langya"; $.ajax ({    URL: "/",    Type: "Post",    data:data1,    success:function (r) {        Console.log (" Xxxxxxxxxxxxxx ");        Console.log (R);    }});

Users can choose different stitching methods according to the situation.

Iv. Summary

And by the way, the trick is that when we get a json, don't rush to create a new model in the class, a class, a Zodiac knock, VS has a very powerful tool that you know can ignore this paragraph.

Source Address GitHub:

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.