1.建立Model對象
/// <summary> /// 使用者實體類 /// </summary> public class UserModel { /// <summary> /// 使用者ID /// </summary> public long UserID { get; set; } /// <summary> /// 使用者顯示名 /// </summary> public string DisplayName { get; set; } /// <summary> /// 使用者名稱 /// </summary> public string RealName { get; set; } }
2.建立Json序列化協助類
/* ============================================================================== * 功能描述:JsonHelper * 創 建 者:RES-WUZHOU * 建立日期:2012/6/21 17:17:08 * ==============================================================================*/using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization.Json;using System.IO;using System.Web.Script.Serialization;namespace Common{ /// <summary> /// JsonHelper /// </summary> public class JsonHelper { /// <summary> /// JSON序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <returns></returns> public static string JsonSerializer<T>(T entity) { var serializer = new JavaScriptSerializer(); return serializer.Serialize(entity); } /// <summary> /// JSON還原序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public static T JsonDeserialize<T>(string jsonString) { var serializer = new JavaScriptSerializer(); return serializer.Deserialize<T>(jsonString); } }}
注意:手動引用 System.Web.Script.Serialization.dll
3.後台 CS方法
public ActionResult Add(string strUserModel) { UserModel userModel = JsonHelper.JsonDeserialize<UserModel>(strUserModel); //.... }
4.前台ajax提交
var userModel = {};userModel.UserID=1;userModel.DisplayName = "張三";userModel.RealName= "zhang";$.ajax({ url: "/user/add", type: "post", data: { strUserModel: $.toJSON(userModel) }, success: function (json) { alert('成功'); }, error: function () { alert("系統異常!"); } });
注意:頁面需引用jquery.js和jquery.json.js