2011-02-11 88 views
21

我有一個函數返回JavaScript和/或HTML的片段。關閉剃刀中的HTML編碼

static public string SpeakEvil() 
{ 
    return "<script>alert('BLAH!!');</script>"; 
} 

在視圖中,Razor完全正確地使用HTML編碼,正如大多數人所期望的那樣。

@StaticFunctions.SpeakEvil() 

我怎麼有剃刀 HTML編碼本,使HTML和JavaScript逐字發出,而任何腳本實際運行?

回答

50

您可以使用Raw()函數,但它主要用於來自數據庫的東西。

針對助手像你這樣我會建議返回一個IHtmlString

static public IHtmlString SpeakEvil() { 
    return new HtmlString("<script>alert('BLAH!!');</script>"); 
} 

你不必這樣,必須在每個調用點調用Raw()

+5

我在非web應用程序中使用RazorEngine。您提出的兩種解決方案都不適用於我,實際上,Html.Raw方法調用給了我以下例外:「無法編譯模板,名稱'Html'在當前上下文中不存在」。如果我有一個MvcHtmlString或一個IHtmlString它仍然html編碼的文本,但不會引發異常。 – 2012-01-16 22:11:26

+4

我在Web應用程序之外使用RazorEngine,並且無法使其工作:(任何想法? – leypascua 2012-03-31 10:53:55

36

使用Html.Raw幫助程序。

@Html.Raw(StaticFunctions.SpeakEvil()) 
4

返回MvcHtmlString(從HtmlString繼承)通過調用MvcHtmlString.Create()方法,像這樣:

public static MvcHtmlString SpeakEvil() 
{ 
    return MvcHtmlString.Create("<script>alert('BLAH!!');</script>"); 
} 


你也可以將它變成一個字符串擴展:

public static MvcHtmlString HtmlSafe(this string content) 
{ 
    return MvcHtmlString.Create(content); 
} 


來源:
http://geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx