2011-11-19 69 views
0

我已經爲UrlHelper寫了一些擴展方法,以便更容易加載或標記。但是,它似乎在瀏覽器中呈現文字文本。這裏是我有:ASP.NET MVC 3:UrlHelper/HtmlHelper的擴展方法編碼爲HTML

public static string Script(this UrlHelper helper, string scriptPath) 
     { 
      return string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath)); 
     } 

這裏是我的.cshtml代碼:

@section HeadContent 
{ 
    @Url.Style("MyStyleName") 
    @Url.Script("MyScriptName") 
    @Url.MetaKeywords("My Keywords") 
    @Url.MetaDescription("Some Description") 
} 

,並在瀏覽器中出現與&lt;script [etc, etc]&gt;

如果我不使用擴展方法,它會如預期的那樣正常工作......我如何使它適用於我的擴展?

回答

2

試試這個:

public static string Script(this UrlHelper helper, string scriptPath) 
{ 
    return MvcHtmlString.Create(string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath))); 
} 
+0

謝謝,朋友!這正是我需要的。唯一的事情是返回類型也必須是MvcHtmlString。再次感謝。 – Matt

+0

歡迎隊友!請考慮爲其他人接受的答案,以瞭解正確的答案。 –

+0

確實。我在等待,直到我能夠接受答案......它說我不能再做3分鐘!瘋狂的事情... – Matt

2

所有HTML傭工需要返回MvcHtmlString。如果你只是返回一個字符串,它將被視爲一個不可信的值,並將被HTML編碼。