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);
}%>
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) %>
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 :)
If you're using Visual Studio 2008 and/or .NET 3.5 you must encode your output like this :
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 :
It's merely a usability improvement; read this for full Jedi credit :
精彩评论