HTML Decode and Encode

2019-04-13 17:14发布

问题:

I have tried to decode the html text that i have in the databse in my MVC 3 Razor application. the html text in the databse is not encoded. I tries httpUtility.decode , server.decode but none of them work. finally i managed to make it work with Html.raw(string)

sample of non working code

@Server.HtmlDecode(item.ShortDescription)
@HttpUtility.HtmlDecode(item.ShortDescription)

Do you know why we can not use html.decode in my case !

I thought this would save some one else from looking for few hours.

回答1:

It works just fine to decode the text, but then it will automatically be encoded again when it's put in the page using the @ syntax.

The Html.Raw method wraps the string in an HtmlString, which tells the razor engine not to encode it when it's put in the page.



回答2:

If you want to display the value as-is without any HTML encoding you could use the Html.Raw helper:

@Html.Raw(item.ShortDescription)

Be warned thought that by doing this you are opening your site to XSS attacks so you should be very careful about what HTML this ShortDescription property contains. If it is the user that enters it you should absolutely ensure that it is safe. You could use the AntiXss library for this.

Do you know why we can not use html.decode in my case !

Because Html.Decode returns a string and when you feed a string to the @() Razor function it automatically Html encodes it again and ruins your previous efforts. That's why the Html.Raw helper exists.