Add CSS references to page's <head> from a partial view

后端 未结 6 2372
感动是毒
感动是毒 2021-02-20 02:21

Is there a way to add CSS references to a page from a partial view, and have them render in the page\'s (as required by the HTML 4.01

6条回答
  •  无人共我
    2021-02-20 02:51

    The following would work only if javascript were enabled. it's a little helper that i use for exactly the scenario you mention:

    // standard method - renders as defined in as(cp)x file
    public static MvcHtmlString Css(this HtmlHelper html, string path)
    {
        return html.Css(path, false);
    }
    // override - to allow javascript to put css in head
    public static MvcHtmlString Css(this HtmlHelper html, 
                                    string path, 
                                    bool renderAsAjax)
    {
        var filePath = VirtualPathUtility.ToAbsolute(path);
    
        HttpContextBase context = html.ViewContext.HttpContext;
        // don't add the file if it's already there
        if (context.Items.Contains(filePath))
            return null;
    
        // otherwise, add it to the context and put on page
        // this of course only works for items going in via the current
        // request and by this method
        context.Items.Add(filePath, filePath);
    
        // js and css function strings
        const string jsHead = "";
        const string jsFunctionStt = "$(function(){";
        const string jsFunctionEnd = "});";
        string linkText = string.Format("", filePath);
        string jsBody = string.Format("$('head').prepend('{0}');", linkText);
    
        var sb = new StringBuilder();
    
        if (renderAsAjax)
        {
            // join it all up now
            sb.Append(jsHead);
            sb.AppendFormat("\r\n\t");
            sb.Append(jsFunctionStt);
            sb.AppendFormat("\r\n\t\t");
            sb.Append(jsBody);
            sb.AppendFormat("\r\n\t");
            sb.Append(jsFunctionEnd);
            sb.AppendFormat("\r\n");
            sb.Append(jsFoot);
        }
        else
        {
            sb.Append(linkText);
        }
    
        return MvcHtmlString.Create( sb.ToString());
    }
    

    usage:

    <%=Html.Css("~/content/site.css", true) %>
    

    works for me, tho as stated, only if javascript is enabled, thus limiting its usefulness a little.

提交回复
热议问题