简体   繁体   English

模型类上的数据属性未在Web Api中发布

[英]Data Attribute on a Model Class not get posted in Web Api

I have written following code to post JSon data to Web Api Class 我编写了以下代码以将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) {
}
});

On Server side i have defined a Post Method with following code 在服务器端,我使用以下代码定义了Post方法

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

The Product is Model class containing Id, Name, Category and Price attribute. 产品是包含ID,名称,类别和价格属性的Model类。

Problem :- When in Model class i add attribute of Required on Id, Name and other properties, data does not get posted and Server return 500 Error with a message ID is Required? 问题:-在模型类中,我在ID,名称和其他属性上添加了Required的属性时,数据未发布,并且服务器返回500错误,且消息ID是必需的吗?

What could be the possible reason of problem or in other words how to post Json data for a model having properties with Attributes. 问题的可能原因是什么,或者换句话说,如何为具有Attributes属性的模型发布Json数据。

You're double-stringifying the product data, and you shouldn't be stringifying it at all; 您正在对产品数据进行两次字符串化,而根本不应该对其进行字符串化; JQuery's ajax method takes a JSON object for data. 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) {
    }
});

Its a better practice to decorate the serverside method which is accepting jquery post with a HttpPost attribute. 更好的做法是装饰服务器端方法,该方法接受带有HttpPost属性的jquery帖子。

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

and follow the same as per dbaseman 并按照每个dbaseman的相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM