1

How do I construct a list of strings in JavaScript and pass it to window.location such that it will show up as List<string> on the C# side of the fence?
(Not using Ajax POST, but instead using window.location)

Example ASP.NET MVC Controller action:

public FileResult GetMyCsvFile(List<string> columnNames)
{
  ...
}

Example JavaScript:

$('export-button').click(function (e) {
    e.preventDefault();

    // TODO: How do I construct the next line(s) such that it can pass a list of strings to my C# controller action?
    window.location = ROOT_PATH + "Home/GetMyCsvFile ... ????
});

1 Answer 1

2

Try

"Home/GetMyCsvFile?columnNames=firstColumn&columnNames=secondColumn...."

As an example, create the <a> tag and give it an id

 @Html.ActionLink("Click me", "Test", "Task", null, new { id = "myLink" })

then in the script (note I've used jquery since that's what you used in the question)

$('#myLink').click(function (e) {
  e.preventDefault();
  // Define the values to pass to the controller
  var firstCol = 'value1';
  var secondCol = 'value2';
  // Construct url with query string
  var path = $(this).attr('href');
  path += '?columnNames=' + firstCol + '&columnNames=' + secondCol;
  // Navigate to the view
  window.location = path;
});

If its a variable list of values, you would need to construct the url in a loop, something like

for (var i = 0; i < myValues.length; i++) {
  if (i === 0) {
    path += '?columnNames=' + myValues[i];
  } else {
    path += '&columnNames=' + myValues[i];
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting idea. Could you show the JavaScript code on how to construct that query string? Thanks!
OK, that could work and it's straight-forward. I wasn't sure if there was a clever way in JS of taking myValues and projecting it to a querystring (other than building the string via a loop). Thanks again. I'll mark this as the answer... unless a better idea comes along. :)

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.