Jquery Ajax method passes value to action
<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是json数据。传递到的Action是
/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 classAClass { Public stringVal1 {Set;Get; } Public stringVal2 {Set;Get; } Public stringVAL3 {Set;Get; } Public stringVal4 {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.
Reprint: http://cnn237111.blog.51cto.com/2359144/838081
Using AJAX to submit data in MVC Jquery Ajax method passed value to action