Always output raw HTML using MVC3 and Razor

2019-04-04 00:04发布

问题:

I’ve got a class with a property that looks like this:

[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }

I’ve already put in the [AllowHtml] attribute to let me submit HTML to this property via the form that I’ve built, but what I want to do is output the value of the property as the raw HTML without it being escaped.

I know I can use Html.Raw(Model.Description) but what I’m looking for is some way of telling Html.DisplayFor(m => m.Description) to always output the raw HTML. Is there an attribute I can use to decorate the properties in my class that I wish to behave like that?

Basically it’s me being lazy—I don’t want to have to remember which properties might contain HTML, so I don’t want to have to think about using Html.Raw(…) when I need to do the above—I’d much rather my Model know what it should do and do it automatically. I’ve tried searching for an answer, but either I’m not phrasing it correctly or there’s no way of doing it :(

Thanks,

回答1:

Change your Description proerpty to return an HtmlString.

Razor does not escape HtmlString values.
(In fact, all Html.Raw does is create an HtmlString)



回答2:

This is actually rather simple (once you know how...). Change your DataType attrib to [DataType(DataType.Html)], and create a partial view, put it in Views/Shared/DisplayTemplates/Html.cshtml, with this:

@model string
@Html.Raw(Model)

Of course you can also not change your DataType attrib, and name the view MultilineText.cshtml instead of Html.cshtml.



回答3:

Just to provide a bit more info here - your issue is that @ will always HtmlEncode unless you have IHtmlString returned - so the issue is sourced at the @ symbol. It's one of the benefits of the razor syntax - its safer to htmlencode than to not. So there is no 'quick' way here since the root of your issue is the @ symbol which will exclude HtmlEncoding if it finds IHtmlString. So - no 'quick' way around this unless you use the old <% syntax which IMHO sucks compared to razor : )