Ganesh
Ganesh

Reputation: 31

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net mvc

Ajax post:

<script type="text/javascript">

        $(document).ready(function () {
            $('#btn').click(function () {
    //            var vals = [];
    //            $('input:checkbox[name=Blanks]:checked').each(function () {
    //                vals.push($(this).val());
    //            });

               // alert(vals);
    //           
                var checkboxData = $(':checked').val();
                $.ajax({
                    // Check the value.
                    type: 'POST',
                    url: '/Home/Extract',
                    data: { 'name': checkboxData },
                    // contentType: 'application/json; charset=utf-8',  // No need to define contentType
                    success: function (result) {

                    },
                    error: function (err, result) {
                        alert("Error in delete" + err.responseText);
                    }

                });
            });

Controller method:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}

My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?

View:

<input type="button" id="btn" value="Extract" style="float:right "/>
@foreach (var m in (List<string>)ViewData["list"])
{
    <ul>
    <li>
    <input type="checkbox" class="myCheckbox"  name="Blanks" id="chk" value="@m"/>
    <img src="@m"  alt=""/>

Upvotes: 0

Views: 8267

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.

Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:

$('#btn').click(function () {
    var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
        return $(this).val();
    }).toArray();

    $.ajax({
        type: 'POST',
        url: '/Home/Extract',
        data: JSON.stringify({ name: values }),
        contentType: 'application/json',
        success: function (result) {

        },
        error: function (err, result) {
            alert("Error in delete" + err.responseText);
        }
    });

    return false;
});

And your controller action signature might look like this:

[HttpPost]
public ActionResult Extract(string[] name)
{
    ...
}

But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.

Upvotes: 1

Related Questions