1

The following code compiles, but doesn't work. As far as I know data-binding expressions allow any valid C# code in them. So what am I doing wrong here?

<asp:Panel CssClass='<%# ("my-class") %>' runat="server" ID="myPannel">
   Blah
</asp:Panel>

<% this.myPannel.DataBind(); %>

I am not getting any errors. It just doesn't render the class attribute whatsoever. I tried without the parenthesis with the same bad luck.

Please note, I need an expression to be evaluated in CssClass attribute and I am expecting the result of that expression to be assigned to the class attribute. This is why I emphasized this by enclosing the string into parenthesis.

7
  • what error are you getting. I would remove the () in the css class assignment. Also,It doesn't need server tags since it's already a hard coded constant Commented Nov 14, 2013 at 22:48
  • 1
    Shouldn't it be <%= "my-class" %>? Commented Nov 14, 2013 at 22:48
  • I am not getting any errors. It just doesn't render the class attribute whatsoever. I tried without the parenthesis with the same bad luck. Commented Nov 14, 2013 at 22:50
  • Did you try = instead of #? Commented Nov 14, 2013 at 22:55
  • @acfrancis, with = it renders like this: <div class="&lt;%= &quot; (my-class) &quot;%>">Blah</div> Commented Nov 14, 2013 at 22:57

1 Answer 1

3

Try this:

<html>
<head runat="server">
    <title></title>
    <script runat="server">
        protected void 
            Page_Load(object sender, EventArgs e)
        {
            this.myPannel.DataBind();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel CssClass='<%# ("my-class") %>' 
            runat="server" 
            ID="myPannel">
            Blah
        </asp:Panel>
    </form>
</body>
</html>

Or just switch the order of your inline code snippets:

<body>
    <% this.myPannel.DataBind(); %>
    <form id="form1" runat="server">
        <asp:Panel CssClass='<%# ("my-class") %>'
            runat="server"
            ID="myPannel">
            Blah
        </asp:Panel>
    </form>
</body>

Or simply use:

<% this.myPannel.CssClass = "my-class";%>
<form id="form1" runat="server">
    <asp:Panel
        runat="server"
        ID="myPannel">
        Blah
    </asp:Panel>
</form>

In all three cases, you have to make sure that the control property is updated before the actual inline code of the control is being processed in the page's life cycle.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.