how to accept value passed through ajax

2019-09-11 03:47发布

问题:

I wrote a code to pass id's of those records which are selected by user by clicking checkbox

on click of bttn submit following code is called

  $("#button").click(function () {

 var selected = $(".a:checked").map(function() {
    return this.id;
}).get();

var urlDistricts = '@Url.Action("selectedId")';
$.ajax({
    type: "POST",

    url: urlDistricts,
    data: { listofid:selected },
    success: function () {

    }
});
});

and to catch this i wrote following in my controller

    [HttpPost]
    public ActionResult selectedId(List<int> listofid)
    {
        return View();
    }

but the listofid is cuming null

回答1:

Set the traditional: true parameter:

$.ajax({
    type: "POST",
    url: urlDistricts,
    traditional: true,
    data: { listofid: selected },
    success: function (result) {

    }
});

Also there seems to be something wrong with your code. You are retrieving the ids of the selected checkboxes. So I can assume that your markup looks like this:

<input class="a" type="checkbox" id="1" name="id1" />
<input class="a" type="checkbox" id="2" name="id2" />
<input class="a" type="checkbox" id="3" name="id3" />
...

I assume that your ids are numeric because you are attempting to bind them to a List<int> in your controller action. Except that this is invalid HTML. Ids cannot start with a number. So one possibility is to use HTML5 data-* attribute on your checkboxes to store this additional metadata:

<input class="a" type="checkbox" data-id="1" name="id1" />
<input class="a" type="checkbox" data-id="2" name="id2" />
<input class="a" type="checkbox" data-id="3" name="id3" />
...

and then:

var selected = $(".a:checked").map(function() {
    return $(this).data('id');
}).get();