I know that if I have a form with multiple elements with the same name I can use this to bind to an array, but is there any way to pass an array from a javascript function to an ASP.NET MVC controller action without using a form?
1 Answer
Yes! Using XmlHttpRequests you can send HTTP GET or POST commands.
Lots of javascript libraries like jQuery make this very easy. For example in jQuery you could do it this way..
<input name="myField" value="1" />
<input name="myField" value="2" />
<input name="myField" value="3" />
<button id="send">Send data to server</button>
Here's the javascript code
$('#send').click(function(e) {
e.preventDefault();
var postParams = {
myField : []
};
$("input[name='myField']").each(function() {
postParams.myField.push($(this).val());
});
$.post("/controller/action", postParams);
return false;
});
This should send a POST request with the following param:
myField=1,2,3
4 Comments
leora
thanks, this worked but i had to add jquery.ajaxsettings.traditional to get the full end to end to work
genxgeek
@Ieora: Hi, what did your controller signature param look like? method(string values) or method(string[] values)?
user_v
@JaJ, method(string values) is fine, but make sure to change postParams to values or you could use method(string postParams)
user_v
It should also be available in Request.QueryString object