Then talk about jquery Ajax methods passed to action (supplemental) _jquery

Source: Internet
Author: User
Tags string format

I wrote an article about the jquery Ajax method passed the value to the action, this article is a supplement to the text
Suppose the method in controller is as follows:

Copy Code code as follows:

Public ActionResult Readperson (Personmodel model)
{
string s = model. ToString ();
return Content (s);
}

Public ActionResult readpersons (list<personmodel> model)
{
string result = "";
if (model = = NULL) return Content (result);
foreach (var s in model)
{
result = S.tostring ();
result = = "-------------";
}
return Content (Result);
}

Where Personmodel is defined as follows:

Copy Code code 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;
}
}

Then the Controller method accepts a single model and a model list respectively. Using AJAX to pass parameters.
For passing a single parameter, assume the JS code is as follows:

Copy Code code 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);

The screenshot from the chrome can be seen as follows:

The data passed is a series of form data, according to the principle of naming matching, can also be obtained data.

Change the option code to the following

Copy Code code as follows:

var option = {
URL: '/test/readperson ',
Type: ' POST ',
Data:JSON.stringify (person),
DataType: ' HTML ',
Success:function (Result) {alert (result);}
};
$.ajax (option);

Where the Json.stringify method is signed as stringify (value [, replacer [, Space]]), the JSON-formatted string is returned according to the ECMA-262 standard stringify function. It can have 3 parameters. Excerpt as follows:
The Stringify function returns a String in JSON format representing a ECMAScript value. It can take three parameters. The parameter is required. The value parameter is a ECMAScript value, which are 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 a array o F Strings and Numbers that acts as a white list for selecting the object properties, that would be stringified. The optional space parameter are a String or number that allows the result to have white spaces injected into it to improve Human readability.
The default ContentType property value is "application/x-www-form-urlencoded"
Quote from Http://www.w3.org/TR/html401/interact/forms.html#adef-enctype

Look at the screenshot of the request header:

Thus, a JSON string is passed to the controller, and MVC can also get the value of the parameter according to the named match.

Change the option to the following code

Copy Code code as follows:

var option = {
URL: '/test/readperson ',
Type: ' POST ',
Data:person,
DataType: ' HTML ',
ContentType: ' Application/json ',
Success:function (Result) {alert (result);}
};

To change the contenttype to JSON format, you get the wrong information.
Although person is a JSON object, the Ajax,data in jquery is automatically converted to query string format key1=value1&key2=value2 This form, which is clearly not in JSON format and therefore error.
To avoid converting to a query string format, you only need to set ProcessData to Fasle. ProcessData default is True.
The note here is that when the contenttype is specified, the data will no longer be submitted as form data, but instead submitted in the form of request data. Can be seen from the request header on the diagram. It is to be noted that the Form data submitted by the formcollection can be obtained. Request Data method Submission is not available through formcollection.
If you set the ProcessData to the default value TRUE.

If you set the ProcessData to False.

In both of these ways, passing the Application/json type will fail because JSON is a text-based format and neither of the above passes is JSON text. So there will be an error.

So, change the option to:

Copy Code code as follows:

var option = {
URL: '/test/readperson ',
Type: ' POST ',
Data:JSON.stringify (person),
DataType: ' HTML ',
ContentType: ' Application/json ',
Success:function (Result) {alert (result);}
};

Then the JSON text is passed, so the value is obtained based on the named match.

For simpler data types, it is sometimes possible to pass a value through a named match without specifying ContentType. But for data types that are slightly more complex, sometimes specifying contenttype: ' Application/json ' is more convenient to handle.
If the action method in a controller is to accept parameters of a list type, such as:
Public ActionResult readpersons (list<personmodel> model)
Then JS constructs the array of such a JSON object first. As follows

Copy Code code 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 simple array of transmission is as data transmission is, Form data is also unrecognized. So make this array again into a JSON form. As follows: The key value of JSON is used in model to match the name of the parameter in the controller.

Copy Code code as follows:

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. This is passed in form data,

Can be seen from the screenshot. However, the data in this format can only get the specified model with 2 elements in the controller, unable to get the value of the attribute in the element.

If you change the data to Json.stringify (JSONP), the following:

Copy Code code as follows:

var option = {
URL: '/test/readpersons ',
Type: ' POST ',
Data:JSON.stringify (JSONP),
DataType: ' HTML ',
Success:function (Result) {alert (result);}
};

So passing the form data of the past is a string of strings that the controller can't identify with, so it doesn't get a value. If you simply set contenttype: ' Application/json ', the data that is not in JSON format is passed, as follows:

So passing the form data of the past is a string of strings that the controller can't identify with, so it doesn't get a value. If you simply set contenttype: ' Application/json ', the data that is not in JSON format is passed, as follows:

Copy Code code as follows:

var option = {
URL: '/test/readpersons ',
Type: ' POST ',
DATA:JSONP,
DataType: ' HTML ',
ContentType: ' Application/json ',
Success:function (Result) {alert (result);}
};

Because the Ajax method of jquery converts 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 occurs.


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

Copy Code code as follows:

var option = {
URL: '/test/readpersons ',
Type: ' POST ',
Data:JSON.stringify (persons),
DataType: ' HTML ',
ContentType: ' Application/json ',
Success:function (Result) {alert (result);}
};

So you can get the true full JSON data.


Finally, a more complex parameter type is shown here to deepen the understanding.
First look at the method signature in controller, TESTCLASSB and a Testclassa list. Slightly complicated.

Copy Code code as follows:

Public ActionResult fortest (TESTCLASSB tb,list<testclassa> TA)
{
string result = "";
return Content (Result);
}

Then look at Testclassa and TESTCLASSB, more complicated. But the structure should be clear, it is not difficult.

Copy Code code as follows:

public class Testclassa
{
public string A1 {set;
Public list<string> A2 {set; get;}
}
public class TESTCLASSB
{
public string B1 {set;
Public INNERTESTCLASSC ITCC {set; get;}
public class INNERTESTCLASSC
{
Public list<int> C1 {set; get;}
}
}

Look at the JS code: gradually construct a JSON format.

Copy Code code 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);
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 JSON string sent out 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"]}]}
Controller receives this JSON string, it can automatically match the parameters. The specific parameters obtained are the following screenshot:

Summarize:

1. Do not specify ContentType, the default is application/x-www-form-urlencoded way to send. At this point, even if the data is sent in JSON format, by default, jquery Ajax will turn him into the form of a query string (which can be modified by modifying the AJAX parameter) and sent out in formdata form.
2. When contenttype is not specified, if the method signature in the controller is relatively simple, then even the Formdata form of data can be obtained from the MVC naming matching rule.
3. When specifying contenttype as ' Application/json ', the data sent must be a string that conforms to the JSON specification. Typically, using json.stringify (jsondata) has better readability, you can get a JSON string. Of course, it's not necessary. The string used for concatenation, as long as it conforms to the JSON specification, can be sent.
4. If the contenttype is ' Application/json ', the data sent is not a string that conforms to the JSON specification, an error occurs.
5. In general, as far as possible, specify ContentType as ' Application/json ' and send JSON strings as the data to be sent, so that the readability is better, and the complex function signature can also play a good match.

This article comes from "one blog" blog

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.