【发布时间】:2018-08-24 11:30:17
【问题描述】:
我在 MVC 视图中有一个数据表,这个数据表中的每条记录都有编辑按钮。
单击编辑按钮时,我需要将记录的 Id 传递给 MVC 操作方法,并从 MVC 操作加载 MVC 视图以进行编辑表单。
这是我的 JQuery 数据表代码。
function PopulateQueryGrid(data) {
$('#querytable').dataTable({
destroy: true,
data: data,
columns: [
{ "data": "type", "name": "Product Type", "autoWidth": true },
{
"data": "isDeleted",
"render": function(data, type, full) {
if (full.isDeleted !== true) {
return "<div style='background-color:PaleGreen;width:100px;text-align:center;padding:2px'> Active </div>";
} else {
return "<div style='background-color:orange;width:100px;text-align:center;padding:2px'> Deleted </div>";
}
}
},
{
"data": "id",
"render": function(data, type, full) {
**// 1 does not work
//return '<input type="button" value="Edit" class="btn btn-info" onclick=\'editItem(' + JSON.stringify(full) + ')\' />';
// 2 does not work
//return '<form asp-controller="ProductType" asp-action="EditProductType" method="get"><input type="hidden" name="typeId" id="typeId" value="' +
//full.id +
//'" /><input type="submit" class="btn btn-info" value="Edit" /></form>';**
}
},
{
"data": "ID",
"render": function(data, type, full) {
return '<input type="button" value="Delete" class="btn btn-danger" onclick=\'deleteItem(' +
JSON.stringify(full) +
')\' />';
}
}
]
});
}
function editItem(item) {
$.ajax({
url: '/ProductType/EditProductType',
data: { typeId : item.id },
type: 'GET',
contentType: 'application/json; charset=utf-8',
error: function() {
alert("error");
}
});
}
function deleteItem(item) {
alert("delete : " + item.id);
}
这是单击编辑按钮后我需要调用的 MVC 操作。
public async Task<IActionResult> EditProductType(int typeId)
{
try
{
var productType = await _productTypesService.GetProductTypeByIdAsync(typeId);
return View(productType);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
以下是同一操作方法的 HTTP Post 版本。
[HttpPost]
public IActionResult EditProductType(ProductTypeViewModel vm)
{
try
{
if (ModelState.IsValid)
{
_productTypesService.EditProductTypeAsync(vm);
return RedirectToAction("Index");
}
return RedirectToAction("EditProductType", vm);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
到目前为止,我尝试了 2 种方法来实现这一点(两者都在上面的数据表代码中进行了注释),但都没有奏效。
- Jquery Ajax
- 为每个编辑按钮创建一个表单,并在单击按钮时将数据提交给 MVC 操作
问题 - 如何从 JS 数据表按钮单击将值传递给 MVC 控制器操作,并从该操作加载 MVC 视图(表单)?
非常感谢您的帮助。谢谢。
【问题讨论】:
-
Ajax 没有意义,因为你想重定向。为什么要使用
<form>? - 你可以只使用一个链接来调用get方法 -
为什么在 EditProductType get 方法中使用了 RedirectToAction?
-
@Stephen Muecke - 谢谢。是的,我使用了一个链接,它可以工作。
-
@Dhiren - 是的,我应该使用 View(modelObj) 而不是 RedirectToAction。编辑了问题。谢谢。
标签: javascript c# jquery datatables asp.net-core-mvc