【发布时间】:2016-09-16 10:59:15
【问题描述】:
我正在开发一个 ASP.NET MVC 4 网站,但我遇到了一些功能问题。我解释一下,我必须选择带有链接复选框的表格中显示的实体:
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
在我的脚本中,我已经能够将每个选中的 Id 复选框存储在一个数组中,如果复选框未选中,则将其删除。但是我不能将数组传递给我的控制器的函数来删除数据库中每个选定的实体。
我使用来自 jquery 的 $.ajax() 通过 POST 请求发送数组(作为 JSON),但我总是收到 500 错误:
- JSON 原语无效
- 空引用
这是我脚本中的函数(我不知道我的数组格式是否有效):
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
然后,POST 在我的控制器中调用以下函数:
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
更新 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
关于这个问题的任何想法?我希望我足够清楚。如果您需要更多详细信息,请不要犹豫。
【问题讨论】:
-
为什么在 MVC 中使用 webMethod?你可以只使用 ActionResult
-
您不需要自己
stringify数据,只需按原样传递数组即可。而且您也不需要自己反序列化,只需接受string[] docsToDelete并让modelbinder 为您处理。 -
@Reddy 我认为这种方式是强制性的,因为我并不期待视图,而是实际视图的异步更新。
-
@DavidHedlund 我试过了,但它仍然无法识别我的参数...
-
@Loïc 你也可以从 ActionResult 传回字符串..
标签: javascript jquery asp.net ajax asp.net-mvc-4