Luke101
Luke101

Reputation: 65278

Razor Alternative to Html.Raw()

I have html being printed out in a method. Here is the code:

@Html.Raw(Html.GenerateTabs())  //works -- but is inconvinent

Is really did not want to do every method like this. Here is the way i wanted to do it. But it does not work. When when I run the code html prints in the browser.

@Html.GenerateTabs()   //prints html in the broswer


<text>@Html.GenerateTabs()</text>  //prints html in the broswer

Is there a razor friendly way to do this?

Upvotes: 8

Views: 16340

Answers (4)

MoXplod
MoXplod

Reputation: 3852

You might want to create a helper in the App_Code folder. The code there is compiled and is available to all your razor views.

Add a file say SiteHelper.cshtml and in there add a helper method

@helper GenerateTabs()
{
   <div>blah</div>
}

Then use it in any razor view as

@SiteHelper.GenerateTabs()

Upvotes: 1

Adam Tuliper
Adam Tuliper

Reputation: 30152

Simply make your GenerateTabs return an MvcHtmlString.

Its similar to the other post here, but why go through another method to output raw html rather than just specify Html.Raw. IE I'm not advocating another method as was done below, but simply ensure your GenerateTabs returns the MvcHtmlString.

Upvotes: 1

Valamas
Valamas

Reputation: 24749

Razor encodes by default. So far I have not found at view level or application level of turning it off.

Maybe make an extension?

    public static MvcHtmlString RawHtml(this string original)
    {
        return MvcHtmlString.Create(original);
    }

...

@Html.GenerateTabs().RawHtml();

Upvotes: 2

Andrew Barber
Andrew Barber

Reputation: 40150

If your code outputs an MvcHtmlString instead of string, it will output properly with the HTML contained therein.

You construct the MvcHtmlString with a static factory method it has, from the string with HTML.

public MvcHtmlString OutputHtml() {
    return MvcHtmlString.Create("<div>My div</div>");
}

then in view:

@OutputHtml()

Upvotes: 12

Related Questions