Search code examples
asp.netinline-code

asp.net databind expression not evaluating


The following code:

aspx file:

<div id="challengedIndependence" class="collegeAccentBlock grid_8 push_1" runat="server" clientidmode="Static" style='display:<%# testMethod %>' >

associated aspx.cs file:

  public string testMethod()
    {
        return "none;";
    }

rendered html file:

<div id="challengedIndependence" class="collegeAccentBlock grid_8 push_1" style="display:&lt;%# testMethod %&gt;">
</div>

I am expecting the result to rendder as ...style:"display:none;"... what am I doing wrong.

Not sure if this should be in the same question: I am doing this because I have multiple lines of code to determine whether this div should be displayed. If there is another way of doing this and an explanation as to why it is better I would also accept that answer.

Reference: Inline expressions referenced on MSDN


Solution

  • If you're going to use an inline expression here, it needs to be the entire content of that attribute, like this:

    <div id="challengedIndependence" class="collegeAccentBlock grid_8 push_1" runat="server" clientidmode="Static" style='<%# testMethod() %>' >
    

    and then return the entire string you want there. It's just rendering it as part of the string.