【问题标题】:Weird link being generated by Html.ActionLinkHtml.ActionLink 生成的奇怪链接
【发布时间】:2013-02-18 16:32:52
【问题描述】:

我有这个:

public class PagesModel
{
    public string ControllerName { get; set; }
    public string ActionName { get; set; }
    public int PagesCount { get; set; }
    public int CurrentPage { get; set; }
    public object RouteValues { get; set; }
    public object HtmlAttributes { get; set; }
}

public static MvcHtmlString RenderPages(this HtmlHelper helper, PagesModel pages, bool isNextAndPrev = false)
{
    //some code
    var lastPageSpan = new TagBuilder("span");
    var firstValueDictionary = new RouteValueDictionary(pages.RouteValues) { { "page", pages.PagesCount } };
    lastPageSpan.InnerHtml = helper.ActionLink(">>", pages.ActionName, pages.ControllerName, firstValueDictionary, pages.HtmlAttributes).ToHtmlString();
    return MvcHtmlString.Create(lastPageSpan.ToString());
}

它生成的链接如下所示:<span><a href="/Forums/Thread?Count=2&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D">>></a></span>

为什么?我究竟做错了什么?当我在设置.innerHtml 之前设置断点时,我看到我的firstValueDictionary 看起来完全正常。怎么回事?

更新:当我用新创建的匿名类型 (new {page = 0}) 替换 RouteValueDictionary 参数时,一切正常。为什么我不能使用预定义的RouteValueDictionary

【问题讨论】:

  • to stirng 正在返回由 helper.Action 抛出的错误
  • 没有。 helper.ActionLink(">>", pages.ActionName, pages.ControllerName, firstValueDictionary, pages.HtmlAttributes) 实际上是在创建错误的链接。

标签: asp.net asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

您使用了错误的 ActionLink 帮助程序重载。试试这样:

lastPageSpan.InnerHtml = helper.ActionLink(
    ">>", 
    pages.ActionName, 
    pages.ControllerName, 
    firstValueDictionary, 
    new RouteValueDictionary(pages.HtmlAttributes) // <!-- HERE!
).ToHtmlString();

这是您使用的overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    object routeValues,
    object htmlAttributes
)

这是您需要使用的correct overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    RouteValueDictionary routeValues,
    IDictionary<string, object> htmlAttributes
)

注意到区别了吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2019-08-28
    • 2012-06-08
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多