Adding StyleSheets Programmatically in Asp.Net

前端 未结 4 1228
粉色の甜心
粉色の甜心 2020-12-03 13:51

I want to add StyleSheets programmatically in the head section but one of the examples I saw seemed to need to many lines of code to add just one style sheet even though I m

4条回答
  •  一整个雨季
    2020-12-03 14:15

    Okay, here is the solution I am currently using :

    I created a helper class :

    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace BusinessLogic.Helper
    {
        public class CssAdder
        {
            public static void AddCss(string path, Page page)
            {
                Literal cssFile = new Literal() { Text = @"" };
                page.Header.Controls.Add(cssFile);
            }
        }
    }
    

    and then through this helper class, all I have to do is :

    CssAdder.AddCss("~/Resources/Styles/MainMaster/MainDesign.css", this.Page);
    CssAdder.AddCss("~/Resources/Styles/MainMaster/MainLayout.css", this.Page);
    CssAdder.AddCss("~/Resources/Styles/Controls/RightMainMenu.css", this.Page);
    //...
    

    So I can add as much as I want with one line of simple code.

    It also works with Masterpage and content page relationships.

    Hope it helps.

    P.S: I don't know the performance difference between this and other solutions but it looks more elegant and easy to consume.

提交回复
热议问题