views:

78

answers:

1

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?

+3  A: 

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
jessegavin
@jessegavin - thanks, this worked but i had to add jquery.ajaxsettings.traditional to get the full end to end to work
ooo