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.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(49)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-09-03 Resize image online 调整图片大小
2019-09-03 Resend a Request by fiddler
2019-09-03 .NET Standard
2016-09-03 git -C
2016-09-03 Common Macros for Build Commands and Properties
2016-09-03 Hearthstone-Deck-Tracker项目的编译
2014-09-03 TeeChart的网络资料
点击右上角即可分享
微信分享提示