开发者

How to grab list of chekboxes and send it to Action in List object?

开发者 https://www.devze.com 2023-02-06 15:48 出处:网络
How to grab list of checkboxes and send it to Action in IList object? I would like to use jQuery to grab list of objects from my page, then create object and send it to action method. In action method

How to grab list of checkboxes and send it to Action in IList object? I would like to use jQuery to grab list of objects from my page, then create object and send it to action method. In action method it should be List .net objec开发者_C百科t.


Assuming you have a list of checkboxes in your markup:

<input type="checkbox" name="c1" checked="checked" />
<input type="checkbox" name="c2" />
<input type="checkbox" name="c3" checked="checked" />
<input type="checkbox" name="c4" />

and a controller action which will take the values:

[HttpPost]
public ActionResult Foo(IEnumerable<bool> values)
{
    ...
}

you could invoke it like this:

var values = $(':checkbox').map(function () {
    return $(this).is(':checked');
}).toArray();

$.ajax({
    url: '<%= Url.Action("Foo") %>',
    type: 'post',
    traditional: true,
    data: { values: values },
    success: function (result) {
        alert('ok');
    }
});

Now let's suppose that you wanted to send the name of the checkbox as well. So that you could have the following action:

[HttpPost]
public ActionResult Foo(IEnumerable<MyViewModel> values)
{
    ...
}

where MyViewModel looks like this:

public class MyViewModel
{
    public string Name { get; set; }
    public bool IsChecked { get; set; }
}

In this case you could send the request as JSON string. This will work out of the box in ASP.NET MVC 3 because there is a JsonValueProviderFactory built-in capable of parsing JSON requests and binding them to strongly typed models but if you are working in older versions you could still define this custom provider manually:

var values = $(':checkbox').map(function () {
    return { name: this.name, isChecked: $(this).is(':checked')};
}).toArray();

$.ajax({
    url: '<%= Url.Action("Foo") %>',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify({ values: values }),
    success: function (result) {
        console.log(result);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号