Search code examples
asp.netcssstylesheethyperlinkmaster-pages

ContentPlaceHolder with link in master page and default.aspx page


I am using

<head runat="server">
    <title></title>
    <link id="Link2" href="~/App_Shared/CSS/AjaxStyle.css" rel="stylesheet" type="text/css"
    runat="server" />
    <asp:ContentPlaceHolder ID="cphHead" runat="server">
    </asp:ContentPlaceHolder>
</head>

this code in master page and in default.aspx page we have its content div like this

<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="server">
</asp:Content>

Now i want to add a new style sheet css file in this content div at default.aspx page like the master page. and in this link href i will give the relative URL (use ~ sign URL)

<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="server">
    <link id="Link1" href="~/App_Shared/CSS/DefaultStyle.css" rel="stylesheet" type="text/css"
    runat="server" />
</asp:Content>

but when it runs it displays me on HTML page source

<link id="Link2" href="../App_Shared/CSS/AjaxStyle.css" rel="stylesheet" type="text/css" />

and

<link id="Link1" href="~/App_Shared/CSS/DefaultStyle.css" rel="stylesheet" type="text/css" />

How to resolve this second one link id="Link1" like the first one id="Link2". I want link1 href converted into a absolute path like link2... but how????


Solution

  • You can add stylesheet by using c# code like this...

    protected void Page_Init(object sender, EventArgs e)
    {
            HtmlLink css = new HtmlLink();
            css.Href = "css/fancyforms.css";
            css.Attributes["rel"] = "stylesheet";
            css.Attributes["type"] = "text/css";
            css.Attributes["media"] = "all";
            Page.Header.Controls.Add(css);
    }
    

    I hope it works as per your requirement...