views:

1054

answers:

3

I'm drawing some checkboxes in a loop and i want to set the text attribute based on the objects that I'm iteration with the loop.

I've something like this:

<asp:CheckBox ID="CheckBox1" runat="server" Text="<%= Html.Encode(item.nome) %>" Checked="true"/>

The problem is that the Html.Encode(item.nome) appears as plain text and if i dont use the quotation marks i get an error.

+3  A: 

Don't use the <asp:CheckBox> control - create a standard html checkbox:

<input type="checkbox" name="cb" checked="checked"><%= Html.Encode(item.nome) %></input>
Tomas Lycken
"Don't use the <asp:CheckBox> control"... In an MVC application.
AaronSieb
Of course - I assumed that was understood, considering the question was specific for ASP.NET MVC.
Tomas Lycken
+6  A: 

Alternatively, use the Html.CheckBox helper.

<%= Html.CheckBox( "CheckBox1", true ) %> <%= Html.Encode(Item.none) %>
Stephen Jennings
I like your style
James Alexander
+1  A: 

You can't mix ASP.NET control tags with the <%= %> syntax. You have two options here:

Use raw HTML for your checkbox, then you can use <%= %> just fine. This style fits better with ASP.NET MVC.

<input type="checkbox" name="cb" checked="checked"><%= Html.Encode(item.nome) %></input>

Or you can use ASP.NET control-friendly data binding syntax:

<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Html.Encode(Container.DataItem, "nome") %>' Checked="true"/>

But to use the data-binding syntax you need a data source control and to be inside a Repeater control. See ASP.NET data binding for more information.

Andrew Arnott