gpt4 book ai didi

c# - ASP.Net MVC RouteData 和数组

转载 作者:IT王子 更新时间:2023-10-29 04:24:49 25 4
gpt4 key购买 nike

如果我有这样的操作:

public ActionResult DoStuff(List<string> stuff)
{
...
ViewData["stuff"] = stuff;
...
return View();
}

我可以用下面的 URL 来点击它:

http://mymvcapp.com/controller/DoStuff?stuff=hello&stuff=world&stuff=foo&stuff=bar

但是在我的 ViewPage 中,我有这段代码:

<%= Html.ActionLink("click here", "DoMoreStuff", "MoreStuffController", new { stuff = ViewData["stuff"] }, null) %>

不幸的是,MVC 不够智能,无法识别该操作采用数组,并展开列表以形成正确的 url 路由。相反,它只是在对象上执行 .ToString(),在列表的情况下,它只列出数据类型。

当目标 Action 的参数之一是数组或列表时,有没有办法让 Html.ActionLink 生成正确的 URL?

-- 编辑--

正如 Josh 在下面指出的,ViewData["stuff"] 只是一个对象。我试图简化问题,但却导致了一个不相关的错误!我实际上使用的是专用的 ViewPage ,因此我有一个紧密耦合的类型感知模型。 ActionLink 实际上看起来像:

<%= Html.ActionLink("click here", "DoMoreStuff", "MoreStuffController", new { stuff = ViewData.Model.Stuff }, null) %>

其中 ViewData.Model.Stuff 被键入为列表

最佳答案

我认为定制的 HtmlHelper 是合适的。

 public static string ActionLinkWithList( this HtmlHelper helper, string text, string action, string controller, object routeData, object htmlAttributes )
{
var urlHelper = new UrlHelper( helper.ViewContext.RequestContext );


string href = urlHelper.Action( action, controller );

if (routeData != null)
{
RouteValueDictionary rv = new RouteValueDictionary( routeData );
List<string> urlParameters = new List<string>();
foreach (var key in rv.Keys)
{
object value = rv[key];
if (value is IEnumerable && !(value is string))
{
int i = 0;
foreach (object val in (IEnumerable)value)
{
urlParameters.Add( string.Format( "{0}[{2}]={1}", key, val, i ));
++i;
}
}
else if (value != null)
{
urlParameters.Add( string.Format( "{0}={1}", key, value ) );
}
}
string paramString = string.Join( "&", urlParameters.ToArray() ); // ToArray not needed in 4.0
if (!string.IsNullOrEmpty( paramString ))
{
href += "?" + paramString;
}
}

TagBuilder builder = new TagBuilder( "a" );
builder.Attributes.Add("href",href);
builder.MergeAttributes( new RouteValueDictionary( htmlAttributes ) );
builder.SetInnerText( text );
return builder.ToString( TagRenderMode.Normal );
}

关于c# - ASP.Net MVC RouteData 和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1752721/

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