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
-
thanks, this worked but i had to add jquery.ajaxsettings.traditional to get the full end to end to workleora– leora09/10/2010 06:20:17Commented Sep 10, 2010 at 6:20
-
@Ieora: Hi, what did your controller signature param look like? method(string values) or method(string[] values)?genxgeek– genxgeek12/09/2011 05:05:06Commented Dec 9, 2011 at 5:05
-
@JaJ, method(string values) is fine, but make sure to change postParams to values or you could use method(string postParams)user_v– user_v02/21/2012 20:30:30Commented Feb 21, 2012 at 20:30
-
It should also be available in Request.QueryString objectuser_v– user_v02/22/2012 05:38:24Commented Feb 22, 2012 at 5:38