1
votes

I want to post data to the server. In the form, I've selected checked checkboxes and retrieve values from them. I used the following code:

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

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

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

In controller I have this:

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

The problem is that in controller I retrieved null values in int[]ids array.

Can anybody help me?

4

4 Answers

0
votes

Values in javascript code are not passed as array of int, try to parse each value as int parseInt($(this).val());.

0
votes

Try this

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

and in controller

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

you should define a complex type and define a property int[] .

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

and in controller

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

just put your checkbox inputs in the form as follow

<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); 
           }
         });