2

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 1

4

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
  • thanks, this worked but i had to add jquery.ajaxsettings.traditional to get the full end to end to work Commented Sep 10, 2010 at 6:20
  • @Ieora: Hi, what did your controller signature param look like? method(string values) or method(string[] values)? Commented 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) Commented Feb 21, 2012 at 20:30
  • It should also be available in Request.QueryString object Commented Feb 22, 2012 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.