如果您有以下内容:
有没有办法与客户端共享JSON对象的数据协定?我真的想让服务器使用订单工厂创建订单,然后将其发送到客户端。客户端使用数据协定添加订单行,并将完全填充的对象作为JSON发回。
我真的想在客户端的JavaScript中执行以下操作:
var order = myService.OrderFactory.GetNewClientOrderRequest();
order.description = "Some New Order";
var orderLine = myService.OrderFactory.GetNewClientOrderLine( order);
orderLine.setProductID( 1234);
orderLine.setQty( 1);
order.AddLine( orderLine);
if( order.SubmitOrder() == true) {
//display confirmation
}
Asp.Net MVC 2的任何示例或网页链接都非常有用。
答案 0 :(得分:1)
嗯,给出一个示例模型:
[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对象实例。