开发者

Html.Encode does not work atleast not as i think it should

开发者 https://www.devze.com 2023-01-16 04:33 出处:网络
开发者_如何学编程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 wi
开发者_如何学编程

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 :

0

精彩评论

暂无评论...
验证码 换一张
取 消