2

我有这个:

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

4

1 回答 1

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
)

注意到区别了吗?

于 2013-02-18T16:48:03.290 回答