views:

48

answers:

3

In asp.net mvc 2 view i am trying to render something if true.

In code below i am trying to use Html.Encode(x) to render value into page but it does render nothing. What is wrong with if statement with html.encode?

Works

<%if (!ViewData.ContainsKey("DisplayQtyPrice")) {%>
    <%: entry.Amount %>
  <%}%>

Does not work

<%if (!ViewData.ContainsKey("DisplayQtyPrice")) {
    Html.Encode(entry.Amount);
  }%>
+4  A: 

You are calling Html.Encode in a code block, but that does not mean the result is being written to the Output stream. Try:

<%if (!ViewData.ContainsKey("DisplayQtyPrice")) {%>
    <%= Html.Encode(entry.Amount) %>
<%}%>

Or shorter

<%= ViewData.ContainsKey("DisplayQtyPrice") ? null : Html.Encode(entry.Amount) %>
driis
I think <%: entry.Amount %> is same as what you suggested in first block of code, and yes that's correct way to do it
mamu
+3  A: 

The problem is that you're not actually adding anything to the response stream. There's nothing wrong with Html.Encode, but you need to do something like this:

<%if (!ViewData.ContainsKey("DisplayQtyPrice")) {
    Response.Write(Html.Encode(entry.Amount));
}%>

EDIT: That said, I think your first version is better, unless you have a problem with angle brackets :)

Scott Anderson
angle brackets no problem, it's just thorny ugly looking, can't show code to kid's otherwise i loose my rights to complain about their handwriting :)
mamu
Just to clarify the above answer: <%= expression %> is a shorthand for exactly Response.Write(expression)
Morten Bergfall
A: 

If you're using Visual Studio 2008 and/or .NET 3.5 you must encode your output like this :

<%= Html.Encode(entry.Amount) %>

Having to do this is everywhere is a drag the .NET developers thankfully simplified ensuring your HTML safety in .NET 4 by removing this need entirely with the syntax :

<%: entry.Amount %>

It's merely a usability improvement; read this for full Jedi credit :

Morten Bergfall