[英]URL.Action with a string array?
I have an array of strings that I need to pass in a query string of Url.Action.我有一个字符串数组,我需要在 Url.Action 的查询字符串中传递这些字符串。
Url.Action("Index", "Resource", new { FormatIds = Model.FormatIDs})
Right now the link is showing up in my browser as System.String[] instead of a query string.现在,该链接在我的浏览器中显示为 System.String[] 而不是查询字符串。 Is it possible to have MVC do this automatically with model binding?是否可以让 MVC 通过模型绑定自动执行此操作?
I need it to bind with my controller action like:我需要它与我的控制器操作绑定,例如:
public ActionResult Index(string[] formatIDs)
To get the list of string to automatically bind using the default binder, you will need to provide them as:要使用默认活页夹获取要自动绑定的字符串列表,您需要将它们提供为:
name=value&name=value2&name=value3
So you'll need to convert your list to something like:所以你需要将你的列表转换成类似的东西:
Index?formatIDs=1&formatIDs=2&formatIDs=3
For use the default model binder, you should end up with something like:要使用默认模型联编程序,您最终应该得到如下内容:
Index?formatIDs=value1&formatIDs=value2&formatIDs=value3
you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility.您可以返回一个名为 HttpValueCollection 的私有集合,即使文档说它是一个使用 ParseQueryString 实用程序的 NameValueCollection。 Then add the keys manually, HttpValueCollection do the encoding for you.然后手动添加密钥,HttpValueCollection 为您进行编码。 And then just append the QueryString manually:然后只需手动附加 QueryString:
var qs = HttpUtility.ParseQueryString("");
new string[] { "value1", "value2", "value3" }.ToList().ForEach(x => qs.Add("formatIDs", x));
Url.Action("Index", "Resource")?@qs
There is another way using the RouteValueDictionary with an array:还有另一种使用带有数组的 RouteValueDictionary 的方法:
@{
var parameters = new RouteValueDictionary();
for (var i = 0; i < Model.CustomList.Count; ++i)
{
parameters.Add($"customListId[{i}]", Model.CustomList[i]);
}
}
usage:用法:
var url = '@Html.Raw(Url.Action("ControllerActioon", "Controller", parameters))';
Still not very elegant - but working.仍然不是很优雅 - 但工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.