好吧,给定一个示例模型:
[DataContract]
public class Item
{
[DataMember]
public string Title { get; set; }
}
您可以创建一个从 JSON 反序列化您的对象的操作过滤器:
/// <summary>
/// Deserialises a DataContract parameter from its JSON equivalence.
/// </summary>
public class JsonParameterFilter : ActionFilterAttribute
{
#region Properties
/// <summary>
/// Gets or sets the parameter name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the type of the parameter.
/// </summary>
public Type Type { get; set; }
#endregion
#region Methods
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
string contentType = request.ContentType;
if (!string.IsNullOrEmpty(contentType) && contentType.ToLower().Contains("application/json"))
{
var serialiser = new DataContractJsonSerializer(this.Type);
var @object = serialiser.ReadObject(request.InputStream);
filterContext.ActionParameters[Name] = @object;
}
}
#endregion
}
并应用于您的操作:
[JsonParameterFilter(Name = "item", Type = typeof(Item))]
public ActionResult ProcessItem(Item item)
{
// Do stuff here
return View();
}
您需要确保发布内容类型为“application/json”的数据:
var item = ItemFactory.GetNewItem();
item.Title = "Something";
var json = $.toJSON(item);
$.ajax({
contentType: "application/json; charset=utf-8"
data: json,
dataType: "json",
type: "post",
url: "Controller/Action",
});
显然,您的客户端库/脚本需要能够创建一个 javascript 对象的实例,该对象可以反序列化为您的服务器端实例。