随着新的Razor视图引擎,我应该返回HtmlHelpers字符串或IHtmlString? [英] With the new Razor View Engine, should my HtmlHelpers return string or IHtmlString?

查看:96
本文介绍了随着新的Razor视图引擎,我应该返回HtmlHelpers字符串或IHtmlString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

剃刀视图引擎,任何时候你直接输出字符串到页面上,它的HTML连接codeD。例如:

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

@"<p>Hello World</p>"

实际上会得到输出到页面:

will actually get output to the page as:

&lt;p&gt;Hello World &lt;/p&gt;

这将在浏览器中显示:

Which would show up in the browser as:

&LT; P&GT;的Hello World&LT; / P&GT;

<p>Hello World </p>

这里的问题,但,当创建HTML辅助,至今,与老ASPX视图引擎,我只想返回一个字符串,并输出到浏览器:

Here's the problem though, when creating Html helpers, till now, with the old aspx view engine I would just return a string, and output that to the browser:

<%= Html.MyCoolHelperMethod(); %>

所以我的问题基本上是这样。难道我这样做:

So my question is basically this. Do I do this:

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

在这种情况下,我可以做到这一点,我CSHTML:

in which case I can just do this in my cshtml:

@Html.MyCoolHelperMethod();

还是我这样做:

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

在这种情况下,我需要做的工作在我CSHTML:

in which case I need to do the work in my cshtml:

@Html.Raw(Html.MyCoolHelperMethod());

显然,第一种方法,使视图看起来非常干净,但我只是想知道,如果共同的模式实际上是在为助手返回一个 IHtmlString 和我一直在这样做是错误的过去。

Obviously the first approach makes the view look a lot cleaner, but I'm just wondering if the common pattern is in fact for helpers to return an IHtmlString and I've been doing it wrong in the past.

推荐答案

在大多数情况下,你应该返回 IHtmlString 的一个实例。这是该模式随后内置的助手*它意味着一个辅助的消费者并不需要担心过多或过少的编码。

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.

而不是使用函数你应该只返回的新实例 HtmlString

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>");
}

*请注意,MVC 3实际使用 MvcHtmlString 作为其助手的返回类型,但是这是一个从MVC 2天缓缴。 (复杂的故事,但在短, IHtmlString 仅在.NET 4中,自MVC 2推出支持.NET 3.5中的 MvcHtmlString 式被引入作为中间步骤)。所有助手打靶MVC 3和更高的应该返回 IHtmlString

*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.

这篇关于随着新的Razor视图引擎,我应该返回HtmlHelpers字符串或IHtmlString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆