构造并传递JavaScript字符串列表给ASP.. NET MVC控制器动作(不使用ajax)

Construct and pass JavaScript string list to ASP.NET MVC Controller action (not using ajax)

本文关键字:控制器 ajax MVC NET JavaScript 字符串 ASP 列表      更新时间:2023-09-26

我如何在JavaScript中构建字符串列表并将其传递给window.location,使其在c#的围栏一侧显示为List<string> ?
(不使用Ajax POST,而是使用window.location)

ASP。. NET MVC控制器动作:

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

示例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 ... ????
});

Try

"Home/GetMyCsvFile?columnNames=firstColumn&columnNames=secondColumn...."
作为一个例子,创建<a>标记并给它一个id
 @Html.ActionLink("Click me", "Test", "Task", null, new { id = "myLink" })

然后在脚本中(注意,我使用了jquery,因为这是你在问题中使用的)

$('#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;
});

如果它是一个变量值列表,则需要在循环中构造url,例如

for (var i = 0; i < myValues.length; i++) {
  if (i === 0) {
    path += '?columnNames=' + myValues[i];
  } else {
    path += '&columnNames=' + myValues[i];
  }
}