I know they now have this in ASP.NET MVC 2.0 <%: Model.CustomerName %>
So when you make HTML helpers is it better to use this way now (provided that you do not want to do HTML encoding)?
I know they now have this in ASP.NET MVC 2.0 <%: Model.CustomerName %>
So when you make HTML helpers is it better to use this way now (provided that you do not want to do HTML encoding)?
Yes, you always want to use <%: Model.CustomerName %>
from now on where you can. Only in very specific cases should you use <%= %>
but try not to use it at all.
If you are creating your own html helpers that you don't want to be encoded, then just return a MvcHtmlString
from them.
E.g. This is a extension method I created to display a tick icon if the passed in value is true.
public static MvcHtmlString MECross(this HtmlHelper html, string value, string text)
{
if (Convert.ToBoolean(value))
{
string spanTag = string.Format("<span class=\"replace icon-cross\" title=\"{0}\"><em></em>{1}</span>",
html.AttributeEncode(text),
html.Encode(text));
return MvcHtmlString.Create(spanTag);
}
return MvcHtmlString.Empty;
}
Note that I Encode
and AttributeEncode
anything that could be dangerous in my extension method and then return a MvcHtmlString
.
HTHs,
Chares
Using <%: %>
should be used whenever you display user entered/submitted data to make your web pages safer.
But sometimes it's just not viable to HTML encode everything. What if you do want to preserve some HTML formatting? In this case you will have to use the regular <%= %>
statement. Let's think of an example where this is the case.
Let's say you have some web content where users can submit their comments. You would like to provide the ability to preserve some formatting (at least line breaks). In this case you will have to preserve <br/>
elements when later displaying these comments. You have two choices:
<br/>
. When you would like to display this comment you could then call <%= Comment %>
<%= Html.Encode(Comment).Replace("\n", "<br/>") %>
Which one is better/safer depends on each particular case, but cleaning up HTML tags is always a nice step to include in any of the two. Everything also depends on allowed formatting definition. Should those be entered as regular tags or something similar to markdown or something completely different depends on you and the code in the end will most certainly depend on it.