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!
Using Html. Raw allows you to output text containing html elements to the client, and have them still be rendered as such. Should be used with caution, as it exposes you to cross site scripting vulnerabilities.
Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.
The Html. Raw Helper Method is used to display HTML in Raw format i.e. without encoding in ASP.Net MVC Razor. Download Code Sample. Download Free Word/PDF/Excel API.
Raw method does not work and I have to use HttpUtility. HtmlDecode(EncodedContent) before I use Html.
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.
There is no practical difference.
The MvcHtmlString.Create
creates an instance of MvcHtmlString
, while the Html.Raw
method creates an instance of HtmlString
, but MvcHtmlString
just inherits from HtmlString
, so they work the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With