Upload values to action using jquery Ajax
< 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" Value = "" />
Data is JSON data. The action to be passed is
/Home/myajax. The method to receive the message in 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 received parameter is formcollection, which 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 " );}
The strength of mvc3 is that it is based on the mechanism of variable parameter name matching, that is, it tries its best to find values with the same variable name.
For the above example, we can even construct a class, as shown below:
Public Class Aclass { Public String Val1 { Set ; Get ;} Public String Val2 { Set ; Get ;} Public String Val3 { Set ; Get ;} Public String Val4 { Set ; Get ;}}
You can set the parameter type to Aclass.
PublicActionresult myajax (Aclass f ){ReturnContent (F. val1 + F. val2 + F. val3 +F. val4 );}
Note: The attribute name of the Aclass class is the JSON key name. It can be matched as long as it complies with the same name.
Post: http://cnn237111.blog.51cto.com/2359144/838081