【发布时间】:2019-03-05 01:48:29
【问题描述】:
我在删除、编辑 jquery 数据表中的行时遇到问题,它一直告诉我这个错误
参数字典包含不可为空类型的参数“id”的空条目
我发现问题在于传递 id,当我将 id 直接放在 Ajax 代码中时效果很好
这是我的Product 模型:
public partial class Products
{
public int ID { get; set; }
// Other properties removed for brevity
}
Controller 中的 delete 方法
public ActionResult delete(int id)
{
db.Configuration.ProxyCreationEnabled = false;
Products d = db.Products.Where(m => m.ID == id).FirstOrDefault<Products>();
db.Products.Remove(d);
db.SaveChanges();
return Json("success", JsonRequestBehavior.AllowGet);
}
这是我的DataTable 行,delete 按钮所在的位置。
{
"data": "id", "render": function (data) {
console.log(data);
return "<a class='btn btn-success' onclick=Editrow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-edit'></i> Edit Record<a/> <a class='btn btn-danger' onclick=DeleteRow(" + data + ")><i class='glyphicon glyphicon-trash'></i> Delete<a/>";
},
这里的data 越来越不确定了。
这是我的 Ajax 代码:
function DeleteRow(id) {
if (confirm("Are You sure to delete this record..?")) {
$.ajax({
type: 'POST',
//url: "/Products/delete/" + id,
url: '@Url.Action("delete", "Products")/' + id,
datatype: 'JSON',
//data: JSON.stringify({ id: id }),
success: function (response) {
if (response == "success") {
alert("Data Deleted successfully..");
window.location.reload();
//$("#myModal").modal('hide');
}
},
error: function (msg) {
alert(msg.responseText);
}
});
}
}
注意:- 当我像这样在 Ajax 代码中直接添加要删除的 id 时,效果很好
url: '@Url.Action("delete", "Products")/' + 10,
【问题讨论】:
-
您尝试过
data: { id: id }并保留@Url.Action()原样吗?我不建议在url上使用查询字符串或路径,而是建议使用data属性设置。 -
我试过了,但它什么也没显示,并且在 inspect/console 中,按钮看起来像这样 /onclick="DeleteRow(undefined)"/
-
通过提到
DeleteRow(undefined),实际上您传递的是'@Url.Action("delete", "Products")/' + undefined,它被解析为空参数并随后抛出不可空类型异常。DeleteRow函数在哪里调用? -
在按钮中:-
return "<a class='btn btn-danger' onclick=DeleteRow(" + data + ")><i class='glyphicon glyphicon-trash'></i> Delete<a/>"; -
@hazem 检查数据值是否没有通过按钮单击传递。
标签: c# asp.net-mvc datatables