由Html.ActionLink生成的奇怪链接

时间:2013-02-18 16:32:52

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

我有这个:

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&amp;Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&amp;Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D">&gt;&gt;</a></span>

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

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

1 个答案:

答案 0 :(得分:4)

您正在使用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
)

注意区别?