gpt4 book ai didi

.net - 使用 MVC 使用列表作为查询字符串参数

转载 作者:行者123 更新时间:2023-12-01 02:54:17 25 4
gpt4 key购买 nike

我有一个看起来像这样的 Action 方法:

public ActionResult DoSomething(string par, IEnumerable<string> mystrings)

我想使用 Url.Action 将其映射到 URL,在 RouteValueDictionary 中传递 mystrings。然而,这只会产生一个只对应于 mystrings.ToString() 的查询字符串。

我怎么能在查询字符串中传递一个列表? MVC 2 中是否有一些功能支持这一点?

澄清:操作方法是使用 GET 而不是 POST 调用的。

我的action方法解析查询字符串没有问题 DoSomething?mystrings=aaa&mystrings=bbb

但是,我无法使用 Url.Action 生成它。传递列表会生成以下查询字符串:mystrings=system.collections.generic.list%601%5bsystem.string%5d

有什么方法可以轻松完成此操作吗?

最佳答案

是的。 Model Binding To A List

编辑:好的,现在我知道你要去哪里了。我不认为 ASP.NET MVC 具有内置功能,因为它旨在从具有唯一名称的路由值生成查询字符串。您可能必须自己滚动。我会在 IEnumerable<String> 上创建一个扩展方法像这样:

public static class Extensions
{
public static string ToQueryString(this IEnumerable<string> items)
{
return items.Aggregate("", (curr, next) => curr + "mystring=" + next + "&");
}
}

然后你可以像这样生成你自己的查询字符串:
<%= Url.Action("DoSomething?" + Model.Data.ToQueryString()) %>

这需要一些润色,因为您应该对字符串进行 UrlEncode 并创建一个尾随的“&”,但这应该给您基本的想法。

关于.net - 使用 MVC 使用列表作为查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3578058/

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