1.创建Model对象
////// 用户实体类 /// public class UserModel { ////// 用户ID /// public long UserID { get; set; } ////// 用户显示名 /// public string DisplayName { get; set; } ////// 用户名 /// 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{ ////// JsonHelper /// public class JsonHelper { ////// JSON序列化 /// ////// /// public static string JsonSerializer (T entity) { var serializer = new JavaScriptSerializer(); return serializer.Serialize(entity); } /// /// JSON反序列化 /// ////// /// public static T JsonDeserialize (string jsonString) { var serializer = new JavaScriptSerializer(); return serializer.Deserialize (jsonString); } }}
注意:手动引用 System.Web.Script.Serialization.dll
3.后台 CS方法
public ActionResult Add(string strUserModel) { UserModel userModel = JsonHelper.JsonDeserialize(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