HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine
Asked Answered
R

2

35

I'm not quite sure how this works yet... trying to find documentation.

In my existing app I've got two different ways of rendering strings in my View

<%: model.something %>
<!-- or -->
<%= model.something %>

The first one is html encoded, and the second one is not.

Is there something similarly short in Razor? All I can find is this, which is the encoded version.

@model.something
Remontant answered 13/11, 2010 at 16:27 Comment(0)
L
57

I guess the best approach would be to use the Raw extension-method: @Html.Raw(Model.Something)

Lessard answered 10/3, 2011 at 12:16 Comment(1)
I received an email from Marcind stating that we should in fact be using this.Remontant
G
15

@Model.Something automatically HTML encodes. If you want to avoid HTML encoding (and you want this only if you are absolutely sure what you are doing) you could use @MvcHtmlString.Create(Model.Something) (basically everything that implements IHtmlString won't be encoded). Phil Haack blogged about the Razor view engine syntax.

Graziano answered 13/11, 2010 at 16:32 Comment(5)
cool thanks. Do you know if they're working on a shorter syntax for sending a string unencoded? something like @=Model.Something would be nice. Not saying that is the right way, just some idea.Remontant
We are looking at something like that for v2 of Razor.Closefitting
I'll be ecstatic when this comes to fruition. In fact, it would be nice to be able to set this in a buddy class as well so that it's set and forget. <DisableHtmlEncode()> for the @Html.EditorFor()Remontant
+1 for the IHtmlString but not the answer. I prefer @Lessard answer which is @Html.Raw(Model.Something)Modal
I just received an email from Marcind stating that we should in fact be using @Html.Raw()Remontant

© 2022 - 2024 — McMap. All rights reserved.