Difference between MvcHtmlString.Create() and Html.Raw()
asp.net-mvc, asp.net-mvc-4, razor
Solution
This is an excellent opportunity to look at the source code that's available to us for ASP.NET (https://github.com/aspnet/AspNetWebStack/).
Looking at HtmlHelper.cs, this is the code for `Html.Raw()`:
public IHtmlString Raw(string value)
{
return new HtmlString(value);
}
public IHtmlString Raw(object value)
{
return new HtmlString(value == null ? null : value.ToString());
}
And this is the code for the MvcHtmlString class:
namespace System.Web.Mvc
{
public sealed class MvcHtmlString : HtmlString
{
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "MvcHtmlString is immutable")]
public static readonly MvcHtmlString Empty = Create(String.Empty);
private readonly string _value;
public MvcHtmlString(string value)
: base(value ?? String.Empty)
{
_value = value ?? String.Empty;
}
public static MvcHtmlString Create(string value)
{
return new MvcHtmlString(value);
}
public static bool IsNullOrEmpty(MvcHtmlString value)
{
return (value == null || value._value.Length == 0);
}
}
}
The most significant difference is that `Html.Raw()` accepts any object, while `MvcHtmlString.Create()` only accepts strings. Also, `Html.Raw()` returns an interface, while the Create method returns an MvcHtmlString object. Lastly, the Create deals with null differently.
Problem
I am creating a MVC-Project. Using MVC 4 and Razor. After building some pages I was wondering: what is the difference between ``` MvcHtmlString.Create() ``` and ``` Html.Raw() ``` Would be nice if you could help me here to understand that. Thanks in advance!