Home  >  Article  >  Web Front-end  >  Let’s talk about Jquery Ajax method passing to action (supplement)_jquery

Let’s talk about Jquery Ajax method passing to action (supplement)_jquery

WBOY
WBOYOriginal
2016-05-16 16:48:46927browse

I wrote an article beforeJquery Ajax method to pass value to action. This article is a supplement to the article
Assume that the method in the controller is as follows:

Copy code The code is as follows:

public ActionResult ReadPerson(PersonModel model)
                            🎜>            string s = model.ToString();
public ActionResult ReadPersons(List model)
                                                                                                 each (vars in model)
                                                                                                                                                                                              sult) ; }




Where PersonModel is defined as follows:





Copy code

The code is as follows:

public class PersonModel

{

public int id                                                                                             set; get; } public int age {
set;
get;
}

public bool gender
{
set;
get;
public string city
{
          set; >
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; >

Then the controller method accepts a single model and a List of models respectively. Pass parameters through ajax.

For the case of passing a single parameter, assume that the js code is as follows:





Copy code


The code is as follows:


var person = {                                                          gender: true,
city: " shanghai"
};

var option = {  ,
success: function (result) { alert(result); }
                                                                                                You can see the following screenshot from chrome:






The data passed is a string of Form data. According to the principle of naming matching, the data can also be obtained.


Change the option code to the following
clipboard_thumb

Copy code
image_thumb The code is as follows:

var option = {

     url: '/test /ReadPerson',

type: 'POST',

The JSON.stringify method signature is stringify ( value [ , replacer [ , space ] ] ). According to the ECMA-262 standard, the stringify function returns a string in JSON format. It can have 3 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 ContentType attribute value is "application/x-www-form-urlencoded"
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-enctype

Look at the screenshot of the request header:





Therefore, what is passed to the controller is a json string, and MVC can also get the value of the parameter based on name matching.

Change the option code to the following


Copy codeclipboard[4]_thumb

The code is as follows:


var option = {
url: '/test/ReadPerson',
type: 'POST',
data: person,
DataType: 'html',
contentType: 'application/json',
success: function (result) { alert(result); }

Change the contentType to json format, and you will get an error message.
Although person is a json object, the ajax and data in jquery will be automatically converted into the query string format key1=value1&key2=value2. Obviously this form is not in json format, so an error will occur.
To avoid conversion to query string format, just set processData to fasle. processData defaults to true.
What needs to be noted here is: when contentType is specified, the data will no longer be submitted in the form of Form Data, but will be submitted in the form of Request Data. It can be seen from the Request Header in the picture. It should be noted that the data submitted by Form Data can be obtained by FormCollection. Submissions via Request Data cannot be obtained through FormCollection.
If processData is set to the default value true.

image_thumb[3]

If processData is set to false.

image_thumb[2]

The above two methods will fail if they are passed according to the application/json type, because json is a text-based format, and what is passed in the above two methods is not json text. So something goes wrong.

Therefore, change the option to:

Copy code The code is as follows:

var option = {
url: '/test /ReadPerson',
type: 'POST',
data:JSON.stringify(person),
dataType: 'html',
contentType: 'application/json',
success: function (result) { alert(result); }
};

then passes the json text, so based on the name matching, the value can be obtained.

clipboard[8]_thumb

For simpler data types, sometimes the value can be passed through named matching without specifying contentType. But for slightly more complex data types, sometimes it is more convenient to specify contentType: 'application/json'.
If the action method in a controller accepts a List type parameter, such as:
public ActionResult ReadPersons(List model)
Then construct such an array of json objects in js first. As follows

Copy code The code is as follows:

var persons = [{
              id: "001",                                               gender: true,
city: "shanghai"
                                                               : "21",
gender: false,
city : "beijing"
}

If a simple array is passed as data, Form Data cannot be recognized. Therefore, this array is formed into a json form again. As follows: The key value of json is model so that it can be the same as the parameter name in the controller and can match.





Copy code
The code is as follows:

var jsonp = { model: persons };

var option = { url: '/test/ReadPersons', type: 'POST', data: jsonp, dataType: 'html', Success: function (result) { alert(result); }         };


Since contentType is not specified, it is the default application/x-www-form-urlencoded. At this time, it is passed in the form of Form Data,






Can be seen from the screenshot. However, for data in this format, the controller can only obtain two elements for the specified model, and cannot obtain the values ​​of the attributes in the elements.

clipboardIf you change data to JSON.stringify(jsonp), as follows:

Copy codeclipboard[1]

The code is as follows:

var option = {

                                                                                                        /ReadPersons', type: 'POST', data: JSON.stringify(jsonp), dataType: 'html', success: function (result) { alert(re sult); }        };

clipboard[2]

Then the Form Data passed is a string. The controller cannot recognize this thing, so the value cannot be obtained. If you only set contentType: 'application/json', and the data passed is not in json format, as follows:

Then the Form Data passed is a string. The controller cannot recognize this thing, so the value cannot be obtained. If you only set contentType: 'application/json', and the data passed is not in json format, as follows:

Copy code The code is 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 will convert data into a query string, it becomes as follows. This string of text certainly does not conform to the json format, so the following error will occur.

clipboard[3]

clipboard[4]


If you set contentType: 'application/json', and set data: JSON.stringify(persons), as follows:

Copy code The code is as follows:

var option = {
     url: '/test /ReadPersons',
type: 'POST',
data: JSON.stringify(persons),
dataType: 'html',
contentType: 'application /json',
success: function (result) { alert(result); }
                     };
Then you can get the truly complete json data

clipboard[5]Finally, a more complex parameter type is demonstrated here to deepen understanding.

First take a look at the method signature in Controller, TestClassB and a List of TestClassA. A little more complicated.



Copy code The code is as follows:public ActionResult Fortest(TestClassB TB,List TA )
                                                                                                                         
Looking at TestClassA and TestClassB again, it is even more complicated. But if the structure is clear, it is not difficult.





Copy code

The code is as follows:


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 }
}

Look at the js code: gradually construct a json format.

Copy code The code is as follows:
$("#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);
varked = {
url: '/test/fortest' ,
type: 'POST',
data: JSON.stringify(jsondata),
dataType: 'html',
contentType: 'application/json' ,
success: function (result ) { alert(result); }
                                                ;

Finally, the json string sent is as follows:
{"TB":{"b1":"b1","ITCC":{"c1":[1,2,3,4]}} ,"TA":[{"a1":"a1","a2":["a","b","x","y"]},{"a1":"a2","a2" :["a2","b2","x2"]}]}
After the Controller receives this json string, it can automatically match the parameters. The specific parameters obtained are as follows:

clipboard[6]

clipboard[7]

Summary:

1. If the contentType is not specified, it will be sent by application/x-www-form-urlencoded by default. Even if the data in json format is sent at this time, by default, jquery's ajax will convert it into the form of a query string (can be modified by modifying the ajax parameters) and send it out in the form of FormData.
2. When contentType is not specified, if the method signature in the controller is relatively simple, then even data in the form of FormData can be obtained by the naming matching rules of MVC.
3. When contentType is specified as 'application/json', the data sent must be a string that conforms to the json specification. Generally, using JSON.stringify(jsondata) has better readability and can obtain a json string. Of course, it's not necessary. Concatenated strings can also be sent as long as they comply with the json specification.
4. If the contentType is 'application/json' and the data sent is not a string that conforms to the json specification, an error will occur.
5. Under normal circumstances, try to specify the contentType as 'application/json' and send a json string as the sending data. This will make it more readable and can also match complex function signatures well. .

This article comes from the “One Blog” blog

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn