【发布时间】:2018-05-20 05:02:06
【问题描述】:
我正在尝试将值从我的这个视图发送到给定的 API 控制器。当我对 json 数据进行硬编码时,它正在工作。当我按下按钮时,我无法发送 id 和品牌名称的数据,因为它是在表中。我如何使它工作?请帮助
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Brand.BrandName)
</th>
<th>
@Html.DisplayNameFor(model => model.ProductName)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Brand.BrandName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td><input type="button" id="Save" /></td>
</tr>
}
</table>
@section scripts {
<script>
$(document).ready(function () {
$("#Save").click(function () {
var brand = { 'id':1, 'brandname': 'abc' }
$.ajax({
url: 'http://localhost:51429/api/brands',
type: 'POST',
dataType: 'json',
data: brand,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});
});
</script>
}
我有一个品牌 API。它发布 API 控制器是
[HttpPost]
public IHttpActionResult Post([FromBody]Brands brand)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Brands.Add(brand);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);
}
【问题讨论】:
-
尝试在您的 JSON 请求中添加
Content-type标头:application/json。此外,在发送之前序列化您的数据:JSON.strinigify(brand)而不仅仅是brand。编辑:在 jQuery 中设置内容类型是在设置调用中添加一个新字段:contentType: "application/json; charset=utf-8" -
我如何从模型中添加 id 和品牌名称并从这个视图发送到 ajax。
-
由于数据在表中,所以我无法访问它的 id 或者我不知道该怎么做。
-
Brands是什么以及生成的 HTML 代码是什么样的? -
Brands 是具有 Id 和 Brandname 的模型。在此视图中点击保存按钮后,它仅将 id 和品牌名称传递给 post api。