【问题标题】:Data Attribute on a Model Class not get posted in Web Api模型类上的数据属性未在 Web Api 中发布
【发布时间】:2013-04-05 17:17:09
【问题描述】:

我已经编写了以下代码来将 JSon 数据发布到 Web Api 类

var product = '{Id: 2012, Name: 'test', Category: 'My Category', Price: 99.5}'

$.ajax({
url: 'api/products',
type: 'POST',
data: JSON.stringify(product),
dataType: 'json',
contentType: "application/json",
success: function (data) {
}
});

在服务器端,我使用以下代码定义了一个 Post 方法

  public HttpResponseMessage Post(Product p)
    {
       //some code to manipulate p and return response 
       return response;
    }

Product 是 Model 类,包含 Id、Name、Category 和 Price 属性。

问题:- 在 Model 类中,我在 Id、Name 和其他属性上添加必需属性时,数据不会被发布并且服务器返回 500 错误,消息 ID 是必需的?

问题的可能原因是什么,或者换句话说,如何为具有属性的模型发布 Json 数据。

【问题讨论】:

  • 请记住,如果您的模型类上的任何属性被标记为私有,它将不会被加载。

标签: asp.net-mvc json asp.net-web-api


【解决方案1】:

您正在对产品数据进行双重字符串化,根本不应该对其进行字符串化; JQuery 的ajax 方法采用 JSON 对象作为数据。

var product = {Id: 2012, Name: 'test', Category: 'My Category', Price: 99.5};

$.ajax({
    url: 'api/products',
    type: 'POST',
    data: product,
    dataType: 'json',
    contentType: "application/json",
    success: function (data) {
    }
});

【讨论】:

    【解决方案2】:

    用 HttpPost 属性装饰接受 jquery post 的服务器端方法是一种更好的做法。

    [HttpPost]
      public HttpResponseMessage Post(Product p)
    {
       //some code to manipulate p and return response 
       return response;
    }
    

    并遵循与 dbaseman 相同的操作

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多