我可以使用这样的Tag帮助程序将要编辑的对象从视图传递到Upsert操作方法...
这是我的Index.cshtml :(请看下面的“编辑”链接
@foreach (var item in Model)
{
<tr>
<td>@item.CategoryID </td>
<td>@item.CategoryName </td>
<td>
<a asp-area="Admin" asp-controller="Category" asp-action="Upsert" asp-route-CategoryID="@item.CategoryID" asp-route-CategoryName="@item.CategoryName">Edit</a>
</td>
</tr>
}
这是我的操作方法:
[HttpPost]
public IActionResult Upsert(Category category)
{
ViewBag.Name = category.CategoryName;
ViewBag.ID = category.CategoryID;
return View();
}
数据将成功传递到Upsert操作方法。
问题:如何在jquery / ajax中传递数据?为此,我需要具有这样的链接:
<a href="/Admin/Category/Upsert/@item.CategoryID" >Edit</a>
我真的不能在jquery中使用Tag-Helpers。我只能在jquery / ajax中传递CategoryID,并且不知道如何传递另一个字段CategoryName并最终将Category对象传递给我的Upsert操作方法? 在下面,我得到调用GetAll方法的数据(因此键入:“ GET”)并在表中呈现数据并为每一行创建一个Edit按钮,我想将完整的对象传递给Upsert方法(因此键入:“ POST” )?我可以在每个循环中创建一个变量,但是在循环外它是未定义的!
$.ajax({
url: "/Admin/Category/GetAll",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += `
<tr>
<td>${item.categoryID}</td>
<td>${item.categoryName}</td>
<td> <div class="text-center">
<a href="/Admin/Category/Upsert/${item.categoryID}" class="btn btn-success">Edit</a>
<a class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
` ;
console.log(item);
});
console.log(result);
$('#tblData tbody').html(html);
},
});
答案 0 :(得分:1)
您应该知道两点:
1。链接是一个Get请求,因此您应将 Upsert 方法上的[HttpPost]
更改为[HttpGet]
。
2。asp-route-*
会生成查询字符串,而不是url中的路由值,如果要在ajax成功函数中生成链接,然后单击它以发送Category对象 Upsert 方法,如下所示更改代码:
$.each(result, function (key, item) {
html += `
<tr>
<td>${item.categoryID}</td>
<td>${item.categoryName}</td>
<td> <div class="text-center">
<a href="/Admin/Category/Upsert?CategoryID=${item.categoryID}&CategoryName=${item.categoryName}" class="btn btn-success">Edit</a>
<a class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
` ;
console.log(item);
});
结果