Suppose this is the case in the cshtml file:
Copy Code code as follows:
<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. The action passed to is/home/myajax. The way you receive it at the action method is as follows:
Copy Code code 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 receive the parameter is FormCollection, also have the same effect.
Copy Code code as follows:
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 a variable-name matching mechanism, which means that it can find as many values as possible with the same variable name. For the above example, we can even construct a class, as follows: public class AClass {
Copy Code code as follows:
public string Val1 {set;
public string Val2 {set;
public string Val3 {set;
public string Val4 {set;
}
Then you can set the parameter type to AClass
Copy Code code as follows:
Public ActionResult Myajax (AClass f) {
Return Content (F.VAL1+F.VAL2+F.VAL3+F.VAL4);
}
Note that the attribute name of the AClass class is the name of the JSON key, so long as it is consistent, it can match and have to say tough.