Friday, July 6, 2012

c# - Load,link CSS files from code behind,dynamically

In one of the projects I had to use different CSS files based on certain condition for a web page.

I have two css files customforms.css for Desktop version of the webpage and styles.css for the Mobile version of the webpage.

protected void Page_Init(object sender, EventArgs e)
{
       string sDeviceType = GetDeviceType();
       switch(sDeviceType)
       {
                case "pc":
                        HtmlLink oDesktopCssCustomLink = new HtmlLink();
                       oDesktopCssCustomLink.Href = "Folder_Name/customforms.css";
                       oDesktopCssCustomLink.Attributes["rel"] = "stylesheet";
                       oDesktopCssCustomLink.Attributes["type"] = "text/css";
                       
                       Page.Header.Controls.Add(oDesktopCssCustomLink);
                break;
                case "phone":
                        HtmlLink oMobileCssStyleLink = new HtmlLink();
                       oMobileCssStyleLink.Href = "Folder_name/style.css";
                       oMobileCssStyleLink.Attributes["rel"] = "stylesheet";
                       oMobileCssStyleLink.Attributes["type"] = "text/css";
                
                       Page.Header.Controls.Add(oMobileCssStyleLink);
                 break;
                 default:
                        //Load the desktop css file
                 break;
        }      
}

No comments: