【问题标题】:Send array of numbers from JS to asp.net MVC action将数字数组从 JS 发送到 asp.net MVC 操作
【发布时间】:2019-06-25 13:23:36
【问题描述】:

我想向我的后台操作发送数字数组,但无论我尝试什么,我都会收到 NULL 或错误。这是我当前的代码。

JS

$.ajax({
        traditional: true,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        type: "POST",
        data: JSON.stringify(groupIds),
        url: '/Admin/ReadMessages',
        error: function (error) {
            swal.fire({
                title: "Something went wrong. Please try again later.",
                type: "error"
            });
        }
    });

MVC

public ActionResult ReadMessages(List<long> groupIds)
{
     return new HttpStatusCodeResult(HttpStatusCode.OK);
}

有什么想法吗?

【问题讨论】:

    标签: c# jquery asp.net http-post


    【解决方案1】:

    试试这个

    var arr= new Array();
    arr.push(1);
    arr.push(2); 
    
    $.ajax({  
        type: "POST",
        url: urlToPost,
        data: JSON.stringify(arr),
        contentType: "application/json"
       });
    

    【讨论】:

    • 你帮助我意识到我做错了什么,错误不在帖子中它在我的数组中...... Ty
    • @Serlok 正是我考虑过的,所以我决定将数组放在这里。所以我很乐意帮助你;)
    【解决方案2】:

    正如@Amin 所说,我意识到,错误在于发送非数组对象,我正在使用 map 函数,它返回了一些 jquery 数组,但是当我实例化 new Array 并发送它时,它只是为了清除其他人完美运行。

    【讨论】:

      【解决方案3】:
      $.ajax({
          traditional: true,
          dataType: "json",
          contentType: 'application/json; charset=utf-8',
          type: "POST",
          data: { 'groupIds': groupIds} ,
          url: '/Admin/ReadMessages',
          error: function (error) {
              swal.fire({
                  title: "Something went wrong. Please try again later.",
                  type: "error"
              });
          }
      });
      

      在控制器中:

      public ActionResult ReadMessages(IEnumerable<long> groupIds))
      {
           return new HttpStatusCodeResult(HttpStatusCode.OK);
      }
      

      【讨论】:

        【解决方案4】:
        $.ajax({
            traditional: true,
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            type: "POST",
            data:{groupIds:groupIds},
            url:'@Url.Action("ReadMessages", "Admin")',
            error: function (error) {
                swal.fire({
                    title: "Something went wrong. Please try again later.",
                    type: "error"
                });
            }
        });
        

        控制器:

        [HttpPost]
        public ActionResult ReadMessages(IEnumerable<long> groupIds))
        {
             return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
        

        【讨论】:

          猜你喜欢
          • 2017-05-12
          • 2012-02-22
          • 2017-03-19
          • 1970-01-01
          • 2014-03-07
          • 1970-01-01
          • 1970-01-01
          • 2019-04-05
          • 1970-01-01
          相关资源
          最近更新 更多