0

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.

1

3 Answers 3

8

Alternatively, use the Html.CheckBox helper.

<%= Html.CheckBox( "CheckBox1", true ) %> <%= Html.Encode(Item.none) %>
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

2 Comments

"Don't use the <asp:CheckBox> control"... In an MVC application.
Of course - I assumed that was understood, considering the question was specific for ASP.NET MVC.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.