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!
I tried the same code but I am getting following error
Unhandled exception at line 9477, column 4 in http://localhost:16919/Scripts/jquery-1.11.1.js
0x800a1391 – JavaScript runtime error: ‘encodeURIContent’ is undefined
Can you help me how to resolve it ? I am using Asp.Net MVC 5.
Thanks in advance