Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Html.Raw MVC helper work?

I use the Html.Raw to print a raw html content, for example when I send some thing like ViewBag.div = "<div> Hello </div>"; from the controller to the view side it does not print a raw html content unless I use the Html.Raw method but if I have an encoded content, like content encoded using jquery and inserted into the database and I want to print it as a raw html content the Html.Raw method does not work and I have to use HttpUtility.HtmlDecode(EncodedContent) before I use Html.Raw so please could anyone explain why it acts in this way and what is the proper situation to use Html.Raw method? or in another way, why Html.Raw does not work when it receives html entities as a parameter instead of html tags?.

like image 782
Mohamad Haidar Avatar asked Jan 30 '16 18:01

Mohamad Haidar


People also ask

What is the use of HTML raw in MVC?

The Html. Raw Helper Method is used to display HTML in Raw format i.e. without encoding in ASP.Net MVC Razor. Please refer the following article for complete information on how to configure Bundles in ASP.Net MVC project.

What is HTML helper method in MVC?

What is HTML Helper in ASP.NET MVC 5? HTML Helpers are methods that return a string. Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application.

What is inline HTML helpers in MVC?

Inline HTML Helpers @helper syntax is used to create reusable inline helper method. They make the code more reusable, as well as more readable. Let's see how to use them. Create an empty ASP.Net MVC Application. Right click the controller and add a controller.

What is the main purpose of HTML helper of ActionLink in ASP.NET MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


1 Answers

Because encoded characters are HTML, and the Raw version of that string is the encoded one.


Html.Raw renders what it is given without doing any html encoding, so with ViewBag.div = "<div> Hello </div>";:

@Html.Raw(ViewBag.div);

Renders

<div> Hello </div>

However, when you have encoded characters in there, such as ViewBag.Something = "&gt;"; the raw version of that is &gt;. To get back to actual html you need to Html.Raw(HttpUtility.HtmlDecode(EncodedContent)); as you've said.

If Html.Raw did do the decoding then it would be confusing, and we would need something that didn't do it. ;-)

like image 160
NikolaiDante Avatar answered Sep 19 '22 19:09

NikolaiDante