Jquery Ajax methods pass values to action _jquery

Source: Internet
Author: User

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.

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.