首先,我們要在前台引入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.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;
}
圖片:
復制代碼 代碼如下:
[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裡面傳入大量的參數,後台也可以直接反序列化為類來點出成員的值了