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

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

<script type="text/javascript" src="/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) http://www.cnblogs.com/joeylee/archive/2012/11/07/2759169.html

 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;
        }
image

 

[Serializable]
    public class EditExam
    {
        public string ExamId { get; set; }
        public string YearTerm { get; set; }
        public string ExamType { get; set; }
        public string ExamDate { get; set; }
        public string ExamName { get; set; }
    }

 

这样就可以很好的避免在前台js里面传入大量的参数,后台也可以直接反序列化为类来点出成员的值了

posted @ 2013-08-09 17:09  梨花驿路  阅读(389)  评论(0编辑  收藏  举报