如何在前台脚本通过json传递数据到后台(使用微软

首先,我们要在前台引入json的脚本,以便于把js对象序列化

<script type="text/javascript" src="https://www.jb51.net/js/jquery.json-2.4.min.js"></script>

然后我们在前台声明一个类,将你要保存的值放到类里面,最后序列化

复制代码 代码如下:


function Save() {
            var examId = '<%=ExamId %>';
            var yearTerm = $("#<%=DDLYearTerm.ClientID %>").val();
            var examType = $("#<%=DDLExamType.ClientID %>").val();
            var examDate = $("#ExamDate").val();
            var examName = $("#ExamName").val();

var exam = {};
            exam["ExamId"] = examId;
            exam["YearTerm"] = yearTerm;
            exam["ExamType"] = examType;
            exam["ExamDate"] = examDate;
            exam["ExamName"] = examName;
            var json = $.toJSON(exam);
            var Result = AjaxController.EditExam(json).value;
            if (Result == "Success")
            {
                alert("保存成功");
                parent.$.fancybox.close();
            }
            else
            {
                alert(Result);
            }
        }

然后我们在后台,进行反序列化,并使用值.因为我们使用ajax所以要在后台的方法上加上[Ajax.AjaxMethod]特性,并且在你前台所在页面的cs里面也要加上Ajax的注册.具体使用看

微软 ajax 库 的使用方法( ajax.ajaxMethod) https://www.jb51.net/article/40764.htm

复制代码 代码如下:


protected void Page_Load(object sender, EventArgs e)
        {
            Ajax.Utility.RegisterTypeForAjax(typeof(Youjiao.xxt.BLL.Controller.AjaxController));
            if (!IsPostBack)
            {
                Databind();
            }
        }

复制代码 代码如下:


[Ajax.AjaxMethod]
        public string EditExam(string value)
        {
            string Result = "";
            try
            {
                if (HttpContext.Current.Request.IsAuthenticated)
                {
                    EditExam editExam = JsonSerializeHelper.DeserializeFromJson<EditExam>(value);
                    ExamController eController = new ExamController();
                    eController.EditExam(editExam);
                    Result = "Success";
                }
                else
                {
                    Result = "会话无效,请重登录!";
                }
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }
            return Result;
        }

图片:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjggfs.html