在 HtmlHelper 扩展方法的 HTML 中添加 css link

Add css link to HTML of HtmlHelper extension method

我有一个如下所示的 HtmlHelper 扩展方法。它 returns PagedList.Mvc.HtmlHelper.PagedListPager.

的实例

PagedListRenderOptions 已指定一些 css 类。每个使用此方法的视图都需要将 link 添加到包含样式的 css 文件中。我发现这是重复和多余的。

有没有办法将 css 添加到此处返回的 MvcHtmlString 实例?

public static MvcHtmlString PagedListPagerCustom(this HtmlHelper helper, UrlHelper Url, PagedList.IPagedList pager)
{
    return PagedList.Mvc.HtmlHelper.PagedListPager(
        helper,
        pager,
        page =>
        {
            return Url.Action("Inspection", "Operation", new { page = page, pageList = true });
        },
        new PagedList.Mvc.PagedListRenderOptions()
        {
            LiElementClasses = new List<string> { "pagerLiElement" },
            ContainerDivClasses = new List<string> { },
            UlElementClasses = new List<string> { "pagerUlElementClasses" },
            DisplayPageCountAndCurrentLocation = false,
            DisplayLinkToFirstPage = PagedList.Mvc.PagedListDisplayMode.Always,
            DisplayLinkToLastPage = PagedList.Mvc.PagedListDisplayMode.Always,
            DisplayLinkToNextPage = PagedList.Mvc.PagedListDisplayMode.Always,
            DisplayLinkToPreviousPage = PagedList.Mvc.PagedListDisplayMode.Always,
            Display = PagedList.Mvc.PagedListDisplayMode.IfNeeded,
            LinkToLastPageFormat = "Last",
            LinkToNextPageFormat = "Next",
            LinkToPreviousPageFormat = "Prev",
            LinkToFirstPageFormat = "1st",
            DisplayEllipsesWhenNotShowingAllPageNumbers = true,
            MaximumPageNumbersToDisplay = 5,
            DisplayLinkToIndividualPages = true,
            ClassToApplyToFirstListItemInPager = "pagerLiElementFirst",
            ClassToApplyToLastListItemInPager = "pagerLiElement",
        }
    );
}

我要补充的csslink是:

<link href="~/Content/css/PageListCustom.css" rel="stylesheet">

不幸的是,这不是很容易实现。 CSS <link> 标记必须位于 <head> 部分,因为 W3C documentation 指定:

This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times. Although LINK has no content, it conveys relationship information that may be rendered by user agents in a variety of ways (e.g., a tool-bar with a drop-down menu of links).

这意味着您不能只将它作为 HtmlHelper 字符串的一部分输出,因为它将在 HTML 页面的正文中使用。您必须改为手动将 CSS link 添加到 <head> 或使用 inline <style> element ,这可以说是不太干净的解决方案。