Load css dynamically in asp.net?

后端 未结 3 1808
借酒劲吻你
借酒劲吻你 2020-12-17 01:33

I\'m creating a content management system where a user can select a css file from their server and the application will parse and store the css. The application will need t

3条回答
  •  粉色の甜心
    2020-12-17 02:12

    I think NullReference gave you a MVC solution because you tagged your post "mvc". If you're using ASP.NET Web forms, you can use the same technique used when generating CSS-links on-the-fly on user-controls. On the page's Page_Init event, do something like the following (in the example below, I'm linking to jquery-ui-CSS):

    protected void Page_Init(object sender, EventArgs e)
    {
         System.Web.UI.HtmlControls.HtmlLink jqueryUICSS;
         jqueryUICSS = new System.Web.UI.HtmlControls.HtmlLink();
         jqueryUICSS.Href = "styles/jquery-ui-1.8.13.custom.css");
         jqueryUICSS.Attributes.Add("rel", "stylesheet");
         jqueryUICSS.Attributes.Add("type", "text/css");
         Page.Header.Controls.Add(jqueryUICSS);
    }
    

    If you want actual elements to be rendered on the header, then use HtmlGeneric control instead of HtmlLink in my example above. It's still the same technique--on Page_Init, add to the Page.Header.Controls collection:

        protected void Page_Init(object sender, EventArgs e)
        {
            System.Web.UI.HtmlControls.HtmlGenericControl mystyles;
            mystyles = new System.Web.UI.HtmlControls.HtmlGenericControl();
            mystyles.TagName = "style";
            string sampleCSS = "body { color: Black; } h1 {font-weight: bold;}";
            mystyles.InnerText = sampleCSS;
            Page.Header.Controls.Add(mystyles);
        }
    

提交回复
热议问题