Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Luke101 Avatar asked Sep 14 '11 03:09

Luke101


People also ask

Why not use HTML Raw?

Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.

What symbol is used by the razor engine in MVC to automatically encode HTML output?

You add code to a page using the @ character When you display content in a page using the @ character, as in the preceding examples, ASP.NET HTML-encodes the output.

What is MvcHtmlString?

Creates an HTML-encoded string using the specified text value. IsNullOrEmpty(MvcHtmlString) Determines whether the specified string contains content or is either null or empty.


3 Answers

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()
like image 158
Andrew Barber Avatar answered Oct 19 '22 03:10

Andrew Barber


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();
like image 28
Valamas Avatar answered Oct 19 '22 04:10

Valamas


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.

like image 22
Adam Tuliper Avatar answered Oct 19 '22 04:10

Adam Tuliper