Search code examples
asp.net-mvc-2asp.net-4.0html-encode

Do you use <%: %> or <%= %> for html helpers in ASP.NET MVC 2.0?


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)?


Solution

  • 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