什么是MvcHtmlString什么时候应该使用它? [英] What is an MvcHtmlString and when should I use it?

查看:186
本文介绍了什么是MvcHtmlString什么时候应该使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.mvchtmlstring%28VS.100%29.aspx\">documentation为 MvcHtmlString 是不是非常有启发性:

The documentation for MvcHtmlString is not terribly enlightening:

重新presents一个HTML-CN codeD字符串,不应该再带codeD。

Represents an HTML-encoded string that should not be encoded again.

这不是我清楚什么这正是影响是。看来,一些HTML辅助方法返回一个 MvcHtmlString ,但我看到网上定制的助手几个例子只是返回一个普通的字符串。

It's not clear to me what exactly the implications of this are. It seems that some HTML helper methods return an MvcHtmlString, but several examples I've seen online of custom helpers just return a regular string.

问题:

什么是 MvcHtmlString

当我应该选择 MvcHtmlString 字符串,反之亦然?为什么呢?

When should I choose MvcHtmlString over string and vice versa? Why?

推荐答案

ASP.NET 4引入了一个新的code块语法&LT;%:%&GT; 。从本质上讲,&LT;%:富%&GT; 转化为&LT;%= HttpUtility.HtmlEn code(富)%&GT; 。该小组正在试图让开发人员可以使用&LT;%:%&GT; 而不是&LT;%=%&GT; 尽可能prevent XSS。

ASP.NET 4 introduces a new code nugget syntax <%: %>. Essentially, <%: foo %> translates to <%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use <%: %> instead of <%= %> wherever possible to prevent XSS.

然而,这引入了问题,如果一个code金块已经连接codeS其结果是,&LT;%:%&GT; 语法重新连接code 的它。这是通过引入IHtmlString接口(在.NET 4中新)的解决。如果富()的在&LT;%:富()%&GT; 返回IHtmlString,在&LT;% :%GT; 语法不会重恩code将其

However, this introduces the problem that if a code nugget already encodes its result, the <%: %> syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %> returns an IHtmlString, the <%: %> syntax will not re-encode it.

MVC 2的助手返回MvcHtmlString,这在ASP.NET 4实现接口IHtmlString。因此,当开发人员使用&LT;%:.html的*()%GT; 在ASP.NET 4中,结果将不会是双恩codeD

MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %> in ASP.NET 4, the result won't be double-encoded.

编辑:

这种新语法的一个直接好处是,你的意见是少许清洁剂。例如,你可以写&LT;%:计算机[什么]%&GT; 而不是&LT;%= Html.En code(计算机[东西])%方式&gt;

An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %> instead of <%= Html.Encode(ViewData["anything"]) %>.

这篇关于什么是MvcHtmlString什么时候应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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