首先,我們要在前臺引入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; }
[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裡面傳入大量的引數,後臺也可以直接反序列化為類來點出成員的值了