Skip to content Skip to sidebar Skip to footer

Do I Need To Encode Attribute Values In Mvc Razor?

In a cshtml file, I'm assigning a string to an attribute. For example: Since @Model.Value string could contain any Unicode char

Solution 1:

Razor performs HTML encoding on strings by default. Depending on where your string is being injected into the HTML stream, this may or may not be the correct encoding to use. If it's not the correct encoding, then you need to perform the correct encoding yourself and be sure to return an MvcHtmlString (i.e. an IHtmlString) to ensure Razor leaves your custom encoding alone.

Since Razor uses HTML encoding, which is technically different from HTML attribute encoding (it's a subset), it's not wrong to use @Html.Raw(Html.AttributeEncode(Model.Value)) to HTML attribute encode the value. At the same time, it's also not necessary, since the default HTML encoding uses the same basic format and will just end up encoding a couple character that otherwise wouldn't need encoded in an HTML attribute value.

On the other hand, in the final case where a string is being injected into the quotes of a JavaScript string, the HTML encoding would absolutely be incorrect, so you'd definitely need to perform the encoding yourself as I did: @Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value)).

Solution 2:

Razor automatically encodes it, so you dont need to.

To be specific it is Encoded using HttpUtility Encode / Decode methods and this happens to anything that is not an IHtmlString such as MvcHtmlString.

Encoding it again would be redundant. If you need to escape this behavor, you need to use the Html.Raw helper, which can be a security risk if the user inputs the model value you are rendering.

Post a Comment for "Do I Need To Encode Attribute Values In Mvc Razor?"