gpt4 book ai didi

javascript - 构造并将 JavaScript 字符串列表传递给 ASP.NET MVC Controller 操作(不使用 ajax)

转载 作者:行者123 更新时间:2023-11-30 17:20:55 24 4
gpt4 key购买 nike

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

示例 ASP.NET MVC Controller 操作:

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

最佳答案

尝试

"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];
}
}

关于javascript - 构造并将 JavaScript 字符串列表传递给 ASP.NET MVC Controller 操作(不使用 ajax),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25150396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com