Is it possible to return an unencoded/unescaped/raw string from a MVC 3 Razor HtmlHelper?
I have created an HtmlHelper
Extension method which returns an encoded string, I have tried returning IHtmlString
and MvcHtmlString
but cannot get the string unencoded/unescaped?
I am trying to reduce the code, 开发者_运维知识库so I dont need Html.Raw()
in this particular instance.
UPDATE
This is an interesting one. I am new to Razor, so added the Method I wanted to a WebViewPage
base class, which obviously didnt work, then created the Method in an HtmlHelperExtension class.
In the view I had @MyMethod()
which was working and rendering the un-encoded html.
I only noticed that I had ommited the "Html.
" bit after seeing Darin Dimitrov's answer, so have added the Html.
and removed the method from the WebViewPage
class, which fixes the existing HtmlHelper I had.
IHtmlString should do the job:
public static class HtmlExtensions
{
public static IHtmlString Foo(this HtmlHelper html)
{
return MvcHtmlString.Create("<a href=\"http://www.google.com\">Google</a>");
}
}
and in your razor view:
@Html.Foo()
would produce in the resulting html:
<a href="http://www.google.com">Google</a>
which is unencoded.
精彩评论