With the new Razor View Engine, should my HtmlHelpers return string or IHtmlString?

后端 未结 1 764
一生所求
一生所求 2021-02-05 03:21

With the Razor View Engine, anytime you output a string directly to the page, it\'s HTML encoded. e.g.:

@\"

Hello World

\"

wil

相关标签:
1条回答
  • 2021-02-05 04:12

    In most cases you should return an instance of IHtmlString. That's the pattern followed by the built-in helpers* and it means that the consumer of a helper does not need to worry about under- or over-encoding.

    Instead of using the Raw function you should probably just return a new instance of HtmlString.

    public static IHtmlString MyCoolHelperMethod(this HtmlHelper helper) {
        return new HtmlString("<p>Hello World</p>");
    }
    

    *Note that MVC 3 actually uses MvcHtmlString as the return type of its helpers but this is a holdover from the MVC 2 days. (Complicated story, but in short, IHtmlString was only introduced in .NET 4 and since MVC 2 supported .NET 3.5 the MvcHtmlString type was introduced as an intermediate step). All helpers targetting MVC 3 and higher should return IHtmlString.

    0 讨论(0)
提交回复
热议问题