zoukankan      html  css  js  c++  java
  • Jquery Ajax方法传值到action

    假设cshtml文件中是这样的:
    <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是json数据。传递到的Action是/Home/MyAjax。那么在Action方法处接收的方式如下:
    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");
            }
    或者接收参数为FormCollection,也有同样的效果。
    public ActionResult MyAjax(FormCollection f)
            {
                string val2 = f["val2"].ToString();
                string val3 = f["val3"].ToString();
                string val4 = f["val4"].ToString();
                return Content("ViewUserControl1");
            }
    MVC3的强悍之处,是它是基于变量参数命名匹配的机制,就是说它尽可能的查找能够有相同变量名字的值。
    对于上面的例子,我们甚至可以构造出一个class,如下:
    public class aclass {
        public string val1 { set; get; }
        public string val2 { set; get; }
        public string val3 { set; get; }
        public string val4 { set; get; }
    }
    那么就可以设置参数类型为aclass
        public ActionResult MyAjax(aclass f)
            {
              return Content(f.val1+f.val2+f.val3+f.val4);
            }
    注意,aclass类的属性名就是json的key的名字,只要符合一致,它就能匹配,不得不说强悍。
  • 相关阅读:
    Zabbix监控MySQL免密码设置
    NFS文件服务器搭建
    Glufster挂载失败Mount failed. Please check the log file for more details解决办法
    CentOS和Redhat救援模式
    CentOS和Redhat单用户模式
    EXSI中Linux安装tools
    Redhat7.5安装glusterfs4
    思科交换机根据mac地址限制主机
    怎么关闭win10防火墙
    [0] WCF开发下,提示HTTP 无法注册 URL 进程不具有此命名空间的访问权限
  • 原文地址:https://www.cnblogs.com/Qiaoyq/p/3142853.html
Copyright © 2011-2022 走看看