在ASP中获取空值.. NET MVC控制器从复选框使用jQuery AJAX



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

$(".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值。

有人能帮我吗?

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

试试这个

  $(".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 });
    });

和in控制器

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

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

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

和in控制器

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

只需将您的复选框输入输入到如下表单

<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>

then post from

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

最新更新