문제

I'm trying to use the Response.Write() method to dynamically insert content in the < head > section of an aspx page. I need to inject a string value from a property on a code-behind object which is a link to my CSS file. However, it is not being processed properly at run time. The object is public on the class and is hydrated in the Page_Load() event. Down in the body of the page I can successfully inject other properties from the Corpoartion object with no problem at all.

Why does this not work in the < head > section?

This is the part that does not expand correctly:

<link href="<%= Corporation.PageStyleSheet %>" rel="stylesheet" type="text/css" />

Here is the entire < head > section:

<head runat="server">
    <title></title>
    <link href="<%= Corporation.PageStyleSheet %>" rel="stylesheet" type="text/css" />
    <script language="JavaScript" type="text/JavaScript" src="cntv_menu.js"></script>
    <script language="JavaScript" type="text/JavaScript" src="cntv_category.js"></script>   
</head>

What is the reason that this will not expand properly?

도움이 되었습니까?

해결책

You can't use <%= %> inside a runat="server" tag, which your <head> tag is.

You can either change it to <%# %> and DataBind to it in the code-behind, or you can make the link tag runat="server", give it an id and assign the attribute from the code behind.

See this answer, which goes into the details.

다른 팁

Use this:

this.myButton.Attributes.Add(attribute, value);

It worked for me :)

the best way to resolve this problem is using OnPreRender

Example:

First, define your tag:

<link href="~/css/your_default.css" type="text/css" runat="server" id="myCSS" />

And on the OnPreRender:

protected override void OnPreRender(EventArgs e){
     base.OnPreRender(e);
     myCSS.Attributes["href"] = "~/css/your_new.css";
}

If you write out the full line you should be ok:

<%
Response.write("<link href=\"" + Corporation.PageStyleSheet + "\" rel=\"stylesheet\" />");
%>

P.S. My syntax may not be completely right, sorry in advance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top