I have a function that returns a snippet of JavaScript and/or HTML.
static public string SpeakEvil()
{
return \"
Return a MvcHtmlString
(Inherits from HtmlString
) by calling the MvcHtmlString.Create()
method like so:
public static MvcHtmlString SpeakEvil()
{
return MvcHtmlString.Create("<script>alert('BLAH!!');</script>");
}
You could also make it into an String extension:
public static MvcHtmlString HtmlSafe(this string content)
{
return MvcHtmlString.Create(content);
}
Source:
http://geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx
You could use the Raw()
function but it's mostly meant for things that come from the database.
For a helper like you have I would suggest returning an IHtmlString
:
static public IHtmlString SpeakEvil() {
return new HtmlString("<script>alert('BLAH!!');</script>");
}
That way you don't have have to call Raw()
at every callsite.
Use the Html.Raw helper.
@Html.Raw(StaticFunctions.SpeakEvil())