Passing list as parameter from AJAX request to MVC controller

I came across this recently when needed to pass array of selected values into MVC controller during Ajax request. Scenario was that on the page I had set of checkboxes and button. User can then make multiple choice selection and submit form using button. Page could look like this:

<ul id="sampleList">
    <li><input type="checkbox" value="1" checked="checked" />text 1</li>
    <li><input type="checkbox" value="2" checked="checked" />test 2</li>
    <li><input type="checkbox" value="3" checked="checked" />test 3</li>
</ul>
<input type="button" id="submitButton" value="submit" />
<span id="spanResults"></span>

Also in the application I have, let’s say, “TestController”. Within this controller I have “GetValue” method, that I want to concatenate input data into a string:

public JsonResult GetValue (List<string> id)
{
return Json(id);
}

Then jQuery code to collect values of checked checkboxes and make Ajaxcall would be as following:

var items = new Array();
$('#sampleList li input:checkbox:checked').each(function() {
    items.push($(this).val());
});
$('#submitButton').click(function() {
    $.ajax({
        type: 'post',
        url: '/Test/GetValues',
        data: { id: items },
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
            $('#spanResults').text(data.join(','));
        },
        error: function(e) {
            alert(e.message);
        }
});

This should hopefully put some light on “how on the earth do I pass list as parameters via Ajax to MVC”. Exactly the same mechanics applies to passing complex types and multiple parameters – just wrapp multiple parameters in complext type and you are done!

One thought on “Passing list as parameter from AJAX request to MVC controller”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.