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
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, this worked but i had to add jquery.ajaxsettings.traditional to get the full end to end to work
@Ieora: Hi, what did your controller signature param look like? method(string values) or method(string[] values)?
@JaJ, method(string values) is fine, but make sure to change postParams to values or you could use method(string postParams)
It should also be available in Request.QueryString object

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.