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