How does Html.Raw MVC helper work?

What does HTML.Raw do?

Is HTML.raw() specific to MVC? On what scenarios we have to use it?

Can you please explain with an example.

 

回答1

Text output will generally be HTML encoded.

Using Html.Raw allows you to output text containing html elements to the client, and have them still be rendered as such.

Should be used with caution, as it exposes you to cross site scripting vulnerabilities.

 

回答2

HtmlHelper.Raw MSDN

Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.

 

How does Html.Raw MVC helper work?

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. ;-)

 

HtmlHelper.Raw Method

      Raw(String)

Returns markup that is not HTML encoded.

C#
public System.Web.IHtmlString Raw (string value);

Parameters

value
String

The HTML markup.

Returns

IHtmlString

The HTML markup without encoding.

 

How to render HTML string in ASP.NET MVC?

You can use the Html.Raw() method for that.

 

Render string to html in MVC

In the controller use

model.MyLink = HttpUtility.HtmlDecode(url);

then in the view use

@Html.Raw(Model.MyLink)

The first converts it to use      

 

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces. 

 

Html Encoding/Decoding & Html.Raw

You should HTML encode as you print in your view (using @Model).

Do not encode or decode anywhere else; do not store encoded content in your database.

 

How does Html.Raw MVC helper work?

上一篇:Android Sepolicy 相关工具


下一篇:MVC源码