Let's talk about passing the JqueryAjax Method to the action.

Source: Internet
Author: User
Assume that the method in the controller is as follows: publicActionResultReadPerson (PersonModelmodel) {stringsmodel. ToString (); returnContent (s);} publicActionResultReadPersons (List & lt; PersonModel & g

Assume that the method in controller is as follows:
Public ActionResult ReadPerson (PersonModel model)
{
String s = model. ToString ();
Return Content (s );
}
 
Public ActionResult ReadPersons (List Model)
{
String result = "";
If (model = null) return Content (result );
Foreach (var s in model)
{
Result + = s. ToString ();
Result + = "-------------";
}
Return Content (result );
}
The PersonModel is defined as follows:
Public class PersonModel
{
Public int id
{
Set;
Get;
}
Public string name
{
Set;
Get;
}
 
Public int age
{
Set;
Get;
}
 
Public bool gender
{
Set;
Get;
}
Public string city
{
Set;
Get;
}
 
Public override string ToString ()
{
String s = string. Format (@ "id: {0}
Name: {1}
Age: {2}
Gender: {3}
City: {4}
", Id, name, age, gender, city );
Return s;
}
}
The controller Method accepts a List of a single model and a model respectively. Use ajax to pass parameters.
When passing a single parameter, assume that the js Code is as follows:
Var person = {
Id: "001 ",
Name: "zhangsan ",
Age: "20 ",
Gender: true,
City: "shanghai"
};
 
Var option = {
Url: '/test/ReadPerson ',
Type: 'post ',
Data: person,
DataType: 'html ',
Success: function (result) {alert (result );}
};
$. Ajax (option );
As shown in chrome:
The transmitted data is a string of Form data. Data can also be obtained based on naming rules.
Change the option code to the following:
Var option = {
Url: '/test/ReadPerson ',
Type: 'post ',
Data: JSON. stringify (person ),
DataType: 'html ',
Success: function (result) {alert (result );}
};
$. Ajax (option );
Here, the JSON. stringify method signature is stringify (value [, replacer [, space]), according to the ECMA-262 standard stringify function returns a string in JSON format. It can have three parameters. The excerpt is as follows:
The stringify function returns a String in JSON format representing an ECMAScript value. it can take three parameters. the first parameter is required. the value parameter is an ECMAScript value, which is usually an object or array, although it can also be a String, Boolean, Number or null. the optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as a white list for selecting the object properties that will be stringified. the optional space parameter is a String or Number that allows the result to have white space injected into it to improve human readability.
The default value of ContentType is "application/x-www-form-urlencoded"
View the request header:

Therefore, the string passed to the controller is a json string, and the parameter value can also be obtained by MVC Based on name matching.
Change the option code to the following:
Var option = {
Url: '/test/ReadPerson ',
Type: 'post ',
Data: person,
DataType: 'html ',
ContentType: 'application/json ',
Success: function (result) {alert (result );}
};
Change contentType to json format to get error information.
Although person is a json object, ajax and data in jquery are automatically converted to the query string format key1 = value1 & key2 = value2. Obviously, this format is not in json format, therefore, an error occurs.
To avoid conversion to query string format, you only need to set processData to fasle. ProcessData is true by default.
Note that when contentType is specified, the Data will not be submitted in Form Data, but will be submitted in Form of Request Data. We can see from the Request Header in the figure. Note that the Data submitted by Form Data can be obtained by FormCollection. If the Request Data method is submitted, it cannot be obtained through FormCollection.
If processData is set to the default value true.

If processData is set to false.

Both of the preceding methods fail to be passed according to the application/json type, because json is based on the text format and none of the above two methods are transmitted as json text. Therefore, an error occurs.
Therefore, change option:
Var option = {
Url: '/test/ReadPerson ',
Type: 'post ',
Data: JSON. stringify (person ),
DataType: 'html ',
ContentType: 'application/json ',
Success: function (result) {alert (result );}
};
The json text is passed, so the value can be obtained based on name matching.

For data types that are relatively simple, sometimes contentType can also be passed through name matching without being specified. However, for data types that are slightly complex, you can specify contentType: 'application/json' to facilitate processing.
If the action method in a controller accepts a List-type parameter, for example:
Public ActionResult ReadPersons (List Model)
Then, js constructs an array of such a json object first. As follows:
Var persons = [{
Id: "001 ",
Name: "zhangsan ",
Age: "20 ",
Gender: true,
City: "shanghai"
},
{
Id: "002 ",
Name: "lisi ",
Age: "21 ",
Gender: false,
City: "beijing"
}
];
A single array is transmitted as data, and Form Data cannot be identified. Therefore, the array is again in json format. Here: The json key value uses model to be the same as the parameter name in controller and can be matched.
Var jsonp = {model: persons };
Var option = {
Url: '/test/ReadPersons ',
Type: 'post ',
Data: jsonp,
DataType: 'html ',
Success: function (result) {alert (result );}
};
Because contentType is not specified, it is the default application/x-www-form-urlencoded. In this case, it is transmitted in Form Data mode,

You can see from this. However, for data in this format, only two elements can be obtained for the specified model in the controller, and attribute values in the element cannot be obtained.


If you change data to JSON. stringify (jsonp), as follows:
Var option = {
Url: '/test/ReadPersons ',
Type: 'post ',
Data: JSON. stringify (jsonp ),
DataType: 'html ',
Success: function (result) {alert (result );}
};

The Form Data passed in the past is a string, and the controller cannot identify this, so it cannot get the value. If you only set contentType: 'application/json', the transmitted data is not in json format, as follows:
Var option = {
Url: '/test/ReadPersons ',
Type: 'post ',
Data: jsonp,
DataType: 'html ',
ContentType: 'application/json ',
Success: function (result) {alert (result );}
};
Because jquery's ajax method converts data into a query string, it becomes the following. This string of text does not conform to the json format, so the following error occurs.


If you set contentType: 'application/json' and set data: json. stringify (persons), as follows:
Var option = {
Url: '/test/ReadPersons ',
Type: 'post ',
Data: JSON. stringify (persons ),
DataType: 'html ',
ContentType: 'application/json ',
Success: function (result) {alert (result );}
};
Then we can get the complete json data.

Finally, we will demonstrate a more complex parameter type for better understanding.
First, let's take a look at the method signature in Controller, TestClassB and a List of TestClassA. Relatively complex.
Public ActionResult Fortest (TestClassB TB, List TA)
{
String result = "";
Return Content (result );
}
It is more complex to look at TestClassA and TestClassB. However, it is not difficult to make the structure clear.
Public class TestClassA
{
Public string a1 {set; get ;}
Public List A2 {set; get ;}
}
Public class TestClassB
{
Public string b1 {set; get ;}
Public InnerTestClassC ITCC {set; get ;}
Public class InnerTestClassC
{
Public List C1 {set; get ;}
}
} View the js Code: gradually construct a json format.
$ ("# Btn"). click (function (){
Var jsondata = {TB :{}, TA: []};
Jsondata. TB. b1 = "b1 ";
Jsondata. TB. ITCC = {};
Jsondata. TB. ITCC. c1 = new Array (1, 2, 3, 4 );
Var ta1 = {};
Ta1.a1 = "a1 ";
Ta1.a2 = new Array ("a", "B", "x", "y ");
Var ta2 = {};
Ta2.a1 = "a2 ";
Ta2.a2 = new Array ("a2", "b2", "x2 ");
Jsondata. TA. push (ta1 );
Jsondata. TA. push (ta2 );
Var option = {
Url: '/test/fortest ',
Type: 'post ',
Data: JSON. stringify (jsondata ),
DataType: 'html ',
ContentType: 'application/json ',
Success: function (result) {alert (result );}
};
$. Ajax (option );
});
Finally, the sent json string is as follows:
{"TB": {"b1": "b1", "ITCC": {"c1": [1, 2, 4] }}, "TA ": [{"a1": "a1", "a2": ["a", "B", "x", "y"] },{ "a1 ": "a2", "a2": ["a2", "b2", "x2"]}
After the Controller receives the json string, it can automatically match the parameter. The specific parameters are as follows:

 

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.