Jquery Ajax methods pass values to action methods

  • 2020-03-30 02:55:20
  • OfStack

Suppose the CSHTML file looks like this:


<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 passed to is /home/myajax. So the way to receive 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 receive 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 a mechanism for naming matches based on variable arguments, meaning that it tries to find values that have the same variable name as possible. For the above example, we can even construct aclass 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 be aclass


    public ActionResult MyAjax(aclass f)        {
          return Content(f.val1+f.val2+f.val3+f.val4);
        }

Notice that the attribute name of the aclass class is the name of the json key, and as long as it matches, it matches.


Related articles: