Pages

Ads 468x60px

Social Icons

Featured Posts

Search

Passing list as parameter from AJAX request to MVC controller

Wednesday, 25 August 2010

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. Html is something like:

[html]
<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>
[/html]

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:

[CSharp]
public JsonResult  GetValue (List<string> id)
{
    return Json(id);
}
[/CSharp]


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

[JavaScript]
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);
        }
});
[/JavaScript]

This should hopefully put some light on "how on the earth do I pass list as parameters via Ajax to MVC".

No comments:

Post a Comment

 

Most Popular