【问题标题】:Getting null values in the ASP.NET MVC Controller from checkboxes using jQuery AJAX使用 jQuery AJAX 从复选框获取 ASP.NET MVC 控制器中的空值
【发布时间】:2011-11-04 11:24:13
【问题描述】:

我想将数据发布到服务器。在表单中,我选择了选中的复选框并从中检索值。我使用了以下代码:

$(".DownloadSelected").click(function () {
    var values = [];
    var chks = $(':checkbox[name="ids"]:checked');

    $(chks).each(function (i) {
        values[i] = $(this).val();
    });

    $.post("/Documents/DownloadSelected/", { ids: values });
});

在控制器中我有这个:

[HttpPost]
public ActionResult DownloadSelected(int[] ids)
{
}

问题是我在控制器中检索了int[]ids 数组中的null 值。

谁能帮帮我?

【问题讨论】:

    标签: jquery asp.net-mvc ajax


    【解决方案1】:

    javascript 代码中的值不作为 int 数组传递,请尝试将每个值解析为 int parseInt($(this).val());

    【讨论】:

      【解决方案2】:

      试试这个

        $(".DownloadSelected").click(function () {
              var chks = $(':checkbox[name="ids"]:checked');
      
              var values= $(chks).each(function (i) {
                 return i.val();
              });
              values.join(',');
              $.post("/Documents/DownloadSelected/", { ids: values });
          });
      

      在控制器中

       [HttpPost]
          public ActionResult DownloadSelected(List<int> ids)
          {
          }
      

      【讨论】:

      • 谢谢,伙计们,我已经用通常的 $.ajax() 函数解决了这个问题,而不是 $.post()
      • 问题是,我必须在 $.ajax() 函数的 ajax 选项中使用 {traditional:true}。
      【解决方案3】:

      您应该定义一个复杂类型并定义一个属性 int[]。

      public class PostModel
      {
          public int[] Ids { get; set; }
      }
      

      在控制器中

      [HttpPost]
      public ActionResult DownloadSelected(PostModel postModel)
      {
      }
      

      【讨论】:

        【解决方案4】:

        只需将您的复选框输入以如下形式输入

        <form id="frm">
        <input type="checkbox"  name="ids" value="1">
        <input type="checkbox"  name="ids" value="2">
        <input type="checkbox"  name="ids" value="3">
        </form>
        

        然后发帖

        var form=$("#frm");
        $.ajax({
                   type: "POST",
                   url: "your action url here",
                   data: form.serialize(), // serializes the form's elements.
                   success: function(data)
                   {
                       alert(data); 
                   }
                 });
        

        【讨论】:

          猜你喜欢
          • 2021-05-09
          • 2013-11-23
          • 2014-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-06
          • 1970-01-01
          • 2014-08-28
          相关资源
          最近更新 更多