1
   <% foreach (var car in Model.AvailableCars)
  { %>
       <label><%car.Text; %></label>

   <% } %>

The above code throws the error

Only assignment, call, increment, decrement, and new object expressions can be used as a statement.

I know I can do it with html helpers, but why won't the above code work?

2 Answers 2

3
<label><%car.Text; %></label> 

should read

<label><%= car.Text; %></label>  
         ^

or you can use

<label><%: car.Text; %></label>
         ^

which will automatically HTML.Encode the value for you.

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

2 Comments

That worked:). I will accept this as the answer as soon as it lets me (in 9 mins)
Unless you have an explicit reason to NOT HtmlEncode the value being displayed I'd recommend always using <%:car.Text%> to write your text to the page. Or in the case of Razor, @car.Text which HtmlEncodes all text by default. You'd have to explicitly use @Html.Raw(car.Text) to not HtmlEncode it with Razor.
1

Add a colon to the car.Text tag to write it to the document, such as:

<label><%: car.Text %></label>

Here's a good explanation of <%: versus <%= asp.net mvc tags: <%: %> vs. <%= %>

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.