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!

Hello world!

let's scratch some heads...Welcome to my technical blog,

This is a very first post here (and I really hope not the last one).

Being in IT industry for a few years now, I realise more and more everyday that having good “knowledge base” is essential for any serious computer professional. Just look here if you do not believe my previous sentence.

Although I had collection of “hacks” and “tricks” it was allover the place. Some bits on my pc at work, some on laptop at home – that obviously is no good when you think “I definitely remember I did it, but how???”.

So the simplest answer to this problem was to create this “webspace”, which I hope also have some value for others as well.

If you by any luck found this place in a fantastic world of Internet, welcome! Feel more than encouraged to leave your fingerprint.

Matt