<script type= "Text/javascript" > $ (document). Ready (function () { $ ("#btn"). Click (function () { $. Ajax ({ type: ' POST ', URL: "/home/myajax", data: { val1: $ ("#txt1"). Val (), val2: $ ("#txt2"). Val ( ), Val3: $ ("#txt3"). Val (), Val4: $ ("#txt4"). Val (), }, DataType: "JSON" } );}); </script><input id= "btn" type= "button" value= "click"/><input id= "txt1" type= "text" value= ""/>< Input id= "txt2" type= "text" value= ""/><input id= "Txt3" type= "text" value= ""/><input id= "TXT4" type= "text" V Alue= ""/>
Data is JSON. The action passed to is/home/myajax. The way to receive it at the action method is as follows:
Public ActionResult Myajax (string val1) { string val2 = request["Val2"]. ToString (); String val3 = request.form["Val3"]. ToString (); String val4 = request.params["Val4"]. ToString (); Return Content ("ViewUserControl1"); }
Or the receiving parameter is FormCollection, also has the same effect.
Public ActionResult Myajax (formcollection f) { string val2 = f["Val2"]. ToString (); String val3 = f["Val3"]. ToString (); String val4 = f["Val4"]. ToString (); Return Content ("ViewUserControl1"); }
MVC3 's strong point is that it is based on the variable parameter naming matching mechanism, that is to say it as far as possible to find the same variable name value. For the example above, we can even construct a class, as follows:
public class AClass {public string Val1 {set; get;} public string Val2 {set; get;} public string Val3 {set; get;} public string Val4 {set; get;}}
Then you can set the parameter type to AClass
Public ActionResult Myajax (aclass f) { return Content (F.VAL1+F.VAL2+F.VAL3+F.VAL4); }
Note that the property name of the AClass class is the name of the JSON key, and as long as it is consistent, it can match and have to say tough.
Add:
Suppose that the method in the controller is 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:
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 list of the model respectively. Use the pass through AJAX parameters.
For cases where a single parameter is passed, the JS code is assumed as follows:
var person = { id: ' 001 ', name: ' Zhangsan ', age : ' Gender:true ', City : ' Shanghai ' };var option = { URL: '/test/readperson ', type: ' POST ', Data:person, dataType: ' HTML ', success: function (Result) {alert (result);} };
From Chrome, you can see the following:
The data passed is a series of form data, according to the principle of naming matching, but also can obtain data.
Change the code of option to the following
var option = { URL: '/test/readperson ', type: ' POST ', data:JSON.stringify (person), DataType: ' HTML ', success:function (Result) {alert (result);} };
Where the Json.stringify method signature is 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 an ECMAScript value. It can take three parameters. The first parameter is required. The value parameter is an ECMAScript value, which are usually an object or array, although it can also bes a String, Boolean , number or null. The optional replacer parameter is either a function that alters the "the" and objects is arrays, or an 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 is a String or number this allows the result to a has white space injected into it to improve Human readability.
The default ContentType property value is "application/x-www-form-urlencoded"
Quoted Http://www.w3.org/TR/html401/interact/forms.html#adef-enctype
Look at the request header:
Therefore, a JSON string is passed to the controller, and MVC is also able to get the value of the parameter based on the naming match.
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 the contenttype to JSON format, then get the error message.
Although the person is a JSON object, Ajax,data in jquery is automatically converted to the query string format key1=value1&key2=value2 This form, which is obviously not in JSON format and therefore an error occurs.
To avoid converting to a query string format, you only need to set ProcessData to Fasle. ProcessData default is True.
It is important to note that when ContentType is specified, the data will no longer be submitted as form data, but instead be submitted in the form of request data. Can be seen from the request header on the diagram. It is important to note that the data submitted by Form data can be obtained by formcollection. The request data submission is not available through formcollection.
True if ProcessData is set to the default value.
If the ProcessData is set to false.
Both of these approaches fail because JSON is a text-based format, and neither of the two approaches is JSON text. So there will be an error.
So, change the option to:
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 a value can be obtained based on a named match.
For simpler data types, sometimes specifying contenttype can also be passed by name matching. However, for data types with slightly more complex points, it is sometimes more convenient to specify contenttype: ' Application/json '.
If the action method in a controller is to accept a list-type parameter, such as:
Public ActionResult readpersons (list<personmodel> model)
Then JS constructs an array of such a JSON object first. As follows
var persons = [{ ID: "001", Name: "Zhangsan", Age : "A", gender:true, City : "Shanghai" }, { ID: "002", Name: "Lisi", Age : "$", Gender:false, City : "Beijing" }
Simply an array pass is passed as data, and Form data is not recognized. Therefore, this array is again formed into a JSON form. As follows: Where the JSON key value is used in model to be able to match the parameter names in the controller.
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 the form data,
Can be seen from it. But in this format, the controller can only get the specified model with 2 elements, unable to get the value of the attribute in the element.
If you change the data to Json.stringify (JSONP), the following:
var option = { URL: '/test/readpersons ', type: ' POST ', data:JSON.stringify (JSONP), dataType: ' HTML ', success:function (Result) {alert (result);}
Then the pass-through form data is a string of strings, and the controller cannot recognize the object, so the value is not obtained. If you just set contenttype: ' Application/json ', instead of the JSON-formatted data, the following:
Then the pass-through form data is a string of strings, and the controller cannot recognize the object, so the value is not obtained. If you just set contenttype: ' Application/json ', instead of the JSON-formatted data, the following:
var option = { URL: '/test/readpersons ', type: ' POST ', Data:jsonp, dataType: ' html ', ContentType : ' Application/json ',
Because jquery's AJAX approach transforms data into a query string, it becomes the same. This string of text certainly does not conform to the JSON format, so the following error occurs.
If 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 you get the really complete JSON data.
Finally, a more complex parameter type is demonstrated here to deepen understanding.
First look at the method signature in the controller, TESTCLASSB and a Testclassa list. Slightly more complex.
Public ActionResult fortest (TESTCLASSB tb,list<testclassa> TA) { string result = ""; return Content (Result);
Look at Testclassa and TESTCLASSB, more complicated. But the structure should be clear, it is not difficult.
public class Testclassa {public string A1 {set; get;} Public list<string> A2 {set; get;} } public class TESTCLASSB {public string B1 {set; get;} Public INNERTESTCLASSC ITCC {set; get;} public class INNERTESTCLASSC {public list<int> C1 {set; get;} }
Look at 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 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"]}]}
After the controller receives the JSON string, it can automatically match the parameters. The specific parameters are as follows:
Summarize:
1. If you do not specify ContentType, the default is to send by application/x-www-form-urlencoded mode. Even if the data is sent in JSON format, by default, jquery's Ajax will turn him into a query string (which can be modified by modifying the Ajax parameters), and send it in formdata form.
2. When contenttype is not specified, if the method signature in the controller is relatively simple, even the Formdata form of the data can be obtained by the MVC naming matching rules.
3. When specifying contenttype as ' Application/json ', the data sent must be a string that conforms to the JSON specification. In general, using Json.stringify (jsondata) is good readability and you can get a JSON string. Of course, it's not necessary. The use of spliced strings, as long as the JSON specification, is also possible to send.
4. If contenttype is ' Application/json ', the data sent is not a string that conforms to the JSON specification, and an error occurs.
5. In general, try to specify ContentType as ' Application/json ' and send the JSON string as the sending data, which is more readable, and can be a good match for complex function signatures.
Ajax, JSON some finishing (2)