【发布时间】:2017-08-18 19:40:53
【问题描述】:
这是产品类别:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
[Range(1, 1000000)]
public decimal Price { get; set; }
[Required]
public string Category { get; set; }
}
这是我的 .cshtml 页面:
<div class="alert alert-success">
<span id="responseMessage"></span>
</div>
<div class="form-group">
<label>Name</label>
@Html.TextBoxFor(x => x.Name)
</div>
<div class="form-group">
<label>Price</label>
@Html.TextBoxFor(x => x.Price)
</div>
<div class="form-group">
<label>Category</label>
@Html.TextBoxFor(x => x.Category)
</div>
<div class="form-group">
<label>Description</label>
@Html.TextBoxFor(x => x.Description)
</div>
<button id="postButton">Ok</button>
这是我的 javascript:
$(document).ready(function () {
$("#postButton").click(function () {
var product = 'product=' +
JSON.stringify({
Name: $('#Name').val(),
Description: $('#Description').val(),
Price: $('#Price').val(),
Category: $('#Category').val()
});
$.ajax({
url: "/api/products/postproduct",
type: "POST",
data: product,
dataType: 'json',
success: function (data, status, xhr) {
$('#responseMessage').html('Insert status: ' +
data.d.status);
},
error: function (xhr, status, error) {
alert('Error occurred: ' + status);
}
});
});
});
这是我的控制器:
public async Task<IHttpActionResult> PostProduct(Product product)
{
if (ModelState.IsValid)
{
await Repository.SaveProductAsync(product);
return Ok();
}
else
{
return BadRequest(ModelState);
}
}
提前谢谢你。 ajax 帖子命中控制器(我在那里设置了一个断点),但是当我将鼠标悬停在产品参数上时,没有值进入。如果您需要更多信息,请告诉我。
【问题讨论】:
-
您是否尝试过放弃
'product='部分而只发送不带字符串化的对象? -
如果您使用的是 .net core,请确保在控制器操作中将
[FromBody]添加到请求模型中。