views:

123

answers:

2

Hi,

I can't get this to work, I want to show a simple list of artist names but always get empty links back.

foreach (Artist artist in Model)
{%>
    <a href="gotosomewhere"><% Html.Encode(artist.Name); %></a>
<%}

I have debugged it, and I'm certain that Model contains a list of artists.

Thanks, Peter

+16  A: 

Change it to:

<%= Html.Encode( artist.Name ) %>

Note the "equals" and the lack of a closing semicolon. This is the format used to output the string value to the response. The other format simply executes the code in the page context, but doesn't automatically write to the response.

tvanfosson
Thanks for pointing this out to me! I knew it would be something stupid :)
Peter
+1  A: 

Indeed, the <% some code %> syntax in ASP.NET translates quite simple to "execute this code".

The <%= some code %> syntax in ASP.NET translates to Response.Write(some code).

Based on this, it becomes clear why <% Html.Encode(...); %> returns nothing. It's encoding your text, but no one is writing it to the response! With <%= Html.Encode(...) %> the ASP.NET compiler turns it into Response.Write(Html.Encode(...)), which will obviously write the encoded text to the response.

Eilon