Lea Cohen
Lea Cohen

Reputation: 8190

Use code behind in CSS

I would like to define a background-color of an element by using a value stored in a resource (resx) file. I'm willing to write that specific part of the CSS in the aspx page instead of in an external CSS file.

I tried using both the <%= %> notation, and the <%# %> notation. However, neithr of them work:

When I try using <%= %>:

.lblHolisticStatus{
    background-color: <%= Resources.ItemList.NeedsSupportColor %> ;
}

I get an error:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

And when I try using <%# %>:

.lblHolisticStatus{
    background-color: <%# Resources.ItemList.NeedsSupportColor %> ;
}

I don't get an error, but no value either. This is how I see it in the view source of the page:

.lblHolisticStatus{
    background-color:  ;
}

Solutions I would rather not do:

This is my full code (minus non-relevant elements):

<head runat="server">
    <style>
        .lblHolisticStatus{
            float:left;
            font-size:1.7rem;
            color:#fff;
            padding: 1rem 2.5rem;
            background-color: <%# Resources.ItemList.NeedsSupportColor %> ;
        }
    </style>
</head>
<body>
    <div class="categoryStatus cf">
        <span class="lblHolisticCategory">
            <%=CategoryName ?? Resources.ItemList.DataNotFound %>
        </span>
        <span class="lblHolisticStatus cls<%= ((eStatus)Type).ToString()%>">
            <%=GetGlobalResourceObject("ItemList", char.ToUpper(((eStatus)Type).ToString()[0]) + ((eStatus)Type).ToString().Substring(1))%>
        </span>
    </div>
</body>

Upvotes: 2

Views: 129

Answers (2)

Amit
Amit

Reputation: 46333

Apparently you can't use <% %> inside <head> when running at the server (<head runat="server">). (here's another reference). What you can do is either run at the client, or move the <style> part down into the <body>.

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148544

There is a workaround :

use : (with #)

 background-color: <%# Resources.ItemList.NeedsSupportColor %> ;

and do in page_load :

this.DataBind()

But I must say you're doing something wrong there. (show us the full code)

Upvotes: 1

Related Questions