Search code examples
htmlasp.netcheckboxinline-code

How do you use inline code to set the value of a checkbox


I have a list of checkboxes that get created dynamically in a loop and when I try to set the value with inline-code, it just gives me the inline code without evaluating it. Here is an example:

<ul>
   <%
    string testValue = string.Empty;
    for(int index = 0; index < 5; index++)
    {
        testValue = "blah" + index;
     %>
        <li>
            <input type="checkbox" runat="server" value="<%= testValue %>" />
        </li>
    <%
    }
     %>
</ul>

and here is the output I'm getting:

<ul>        
<li>
   <input name="ctl00$MainContent$ctl00" type="checkbox" value="&lt;%= testValue %>" />
</li>

<li>
    <input name="ctl00$MainContent$ctl00" type="checkbox" value="&lt;%= testValue %>" />
</li>

<li>
     <input name="ctl00$MainContent$ctl00" type="checkbox" value="&lt;%= testValue %>" />
</li>

<li>
      <input name="ctl00$MainContent$ctl00" type="checkbox" value="&lt;%= testValue %>" />
</li>

<li>
      <input name="ctl00$MainContent$ctl00" type="checkbox" value="&lt;%= testValue %>" />
</li>
</ul>

Can someone PLEASE help me with this?


Solution

  • Since you are using runat="server" already, I would recommend just using server-side controls to manage your dynamic content, like this:

    <ul>
        <asp:Repeater ID="Repeater1" runat="server" 
                      OnItemDataBound="Repeater1_ItemDataBound">
            <ItemTemplate>
                <li>
                    <asp:CheckBox id="check1" runat="server" />
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ul>
    

    Now when you bind the repeater (OnItemDataBound), you can access the .Text property of the checkbox, like this:

    protected void Repeater1_ItemDataBound(Object sender, RepeaterItemEventArgs e) 
    {
        // This event is raised for the header, the footer, separators, and items.
        // Execute the following logic for Items and Alternating Items.
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
        {
            CheckBox theCheckBox = e.Item.FindControl("check1") as CheckBox;
    
            // Make sure we found the check box before we try to use it
            if(theCheckBox != null)
            {
                theCheckBox.Text = "Your Text Value Here";
            }
        }
    }
    

    Note: Using code-behind allows you to leverage the power of the Visual Studio debugger more easily and use IntelliSense to help reduce typos and catch more problems at compile-time versus run-time.