0

I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding.

Previously:

<%= Html.Encode( ViewData['username'] ) %>

Would be equivalent to:

<%=h ViewData['username'] %>

Anyone have any ideas how I could do this, maybe using an extension method or something?

1
  • ToString() will be called in <%= x %> to convert x to a string if necessary. So use your own "strings" instead of strings, and override the string conversion method and/or the string implicit conversion operator. Or upgrade to a version of ASP.NET MVC that already does exactly this. :)
    – bzlm
    Sep 11, 2011 at 15:43

2 Answers 2

7

It's not so clean as an operator overload, but I used the following extension method:

public static string Safe(this string sz)
{
    return HttpUtility.HtmlEncode(sz);
}

So in my aspx id do:

<%= this.ViewData["username"].Safe() %>

Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.

0
-2

NOTE: This is an ugly and untested hack, I don't think I'd ever do this

public static String h (this System.Object o, System.Object viewData)
{
    return Html.Encode(viewData);
}

I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.

this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job:

<%=h(ViewData['username']) %>
1
  • 1
    You should be ashamed of yourself!
    – bzlm
    Oct 3, 2009 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.