Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvcHtmlString and HtmlString seem pretty useless wrappers around a simple string?

I'm looking at the source code for MvcHtmlString and its base class HtmlString, both of which seem like useless wrappers around a string.

I remember one time earlier I did this exercise and saw the benefit but can't remember it now. At the time I spent many hours studying the MvcHtmlString and one of the things I learnt was that its (static obviously) factory method Create was made redundant by the introduction of a parameterless ctor on the MvcHtmlString class.

But I can't seem to remember or find my analysis or notes on what service these classes add over and above an ordinary string.

What's the use of these classes then?

like image 838
Water Cooler v2 Avatar asked Dec 21 '22 00:12

Water Cooler v2


1 Answers

Their main purpose is to implement the IHtmlString marker interface which was introduced in ASP.NET 4.0.

This is part of the Auto-Encoding feature of ASP.NET 4.0+. Before ASP.NET 4.0 we had only this syntax available:

<%= … %>

And this was simply injecting the string into the generated HTML. In 4.0 following syntax has been added:

<%: … %>

Which is a syntax we all should be using now. The difference with old syntax is that the string will be HTML encoded by the framework.

But there are some cases when we don't want to encode the string as it is already a properly encoded HTML (for example it is an output from HtmlHelper). In such cases we should return a class which implements IHtmlString. The new syntax will be happy to accept this instead of string and will not try to encode this, it will just output the string returned by .ToHtmlString() method of the interface. This way we don't have two think if we should use old syntax or new syntax.

Now one can ask why there is a HtmlString and MvcHtmlString class. The answer is Razor. The Razor syntax:

@...

is also encoding everything by default. Now the Razor was introduced in ASP.NET MVC 2.0 which was able to work on .Net Framework 3.5 and there was no IHtmlString or HtmlString there - MvcHtmlString was the marker class for Razor, now it is kept only for backward compatibility.

like image 193
tpeczek Avatar answered Mar 29 '23 23:03

tpeczek