【问题标题】:Pass an array as parameter to a controller from an ajax call in JavaScript将数组作为参数从 JavaScript 中的 ajax 调用传递给控制器
【发布时间】: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


【解决方案1】:

如果您从$.ajax 正确传递一个整数数组(即您的docsArray 应该具有类似[15,18,25,30,42,49] 的值)那么您应该尝试:

[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
    //int id; 
    //string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
  try {
    foreach (int docId in docsArray)
    {
        //int.TryParse(docId, out id);
        dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
    }
    return "Success ";
  }
  catch {
        return "Error";
  }
}

更新:

你的 javascript 代码应该是:

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 ');
        },
        error: function (result) {
            alert('Fail ');
        }
    });
}

【讨论】:

  • 它必须解析它,因为我的 ID 是“checkbox123”
  • "checkbox123" 无法在int 中解析,您必须只传递像 123 这样的整数 id.. 你可以看到:stackoverflow.com/questions/2099164/…
  • 我怀疑 AJAX 是否会首先使用此方法。它不是 ActionResult
  • 感谢@Reddy,添加了 ActionResult
  • @Sachin @Reddy 所以,我将 Ids 更改为整数(在我看来,当我在数组中推送值时)。但我再次遇到异常:System.ArgumentException - Primitive JSON invalid : undefined
【解决方案2】:

也许 JSON 数组中的数据类型不是字符串? (如果你有一个[45,64,34,6] 形式的数组,或者像[345,"wef4"] 这样的混合数组,就会发生这种情况。

要确保某些内容是 Javascript 中的字符串,您可以这样做:var string = "".concat(otherVar);

【讨论】:

  • 我数组中的每个元素都是在我的视图中定义的,例如“checkbox123”,在控制台中我打印每个值。
【解决方案3】:

尝试将您的 ajax 数据更改为类似的内容..

 data : JSON.stringify({'docsToDelete':docsArray}),

【讨论】:

    【解决方案4】:

    对您的代码进行这些更改。


    在 Jquery 中

    data: docsArray, 无需对数组进行字符串化


    在控制器中

        [Authorize]                                                //remove [WebMethod]
        public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
        {
            int id; 
            string[] arrayDocs = docsToDelete;     //no need of deserilization
    
            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(id);    //return id back to ajax call...
        }
    

    【讨论】:

    • 我可能遗漏了什么,但 VS 说 ActionResult 不能是整数...... Cast 也不起作用。
    • @Loïc 我的错,应该是return Json(id);
    • 好吧,有道理,我试试
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 2017-04-18
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多