Franco Fittipaldi
Franco Fittipaldi

Reputation: 43

HttpUtility HtmlDecode. Why do i need this?

I have an ASP.NET MVC controller that returns a view. In this view i create some html. For example

@Html.ActionLink(HttpUtility.HtmlDecode("¿Olvidó su contraseña?"), "ForgotYourPassword", "Account", null, new { style = "color: white; text-decoration: none;"})

The thing is, that this app needs to handle some special characters for example the ñ.

The code above works fine, the html renders without problems. But the thing is that i dont understand why should i use:

HttpUtility.HtmlDecode("¿Olvidó su contraseña?")

This line will simply return "¿Ólvido su contraseña?", but if instead of using HtmlDecode i simply use:

@Html.ActionLink("¿Ólvido su contraseña?", "ForgotYourPassword", "Account", null, new { style = "color: white; text-decoration: none;"})

The browser wont be able to show the HTML properly and it will have character encoding problems.

Why can't I simply use "¿Ólvido su contraseña?" ?. After all HttpUtility.HtmlDecode("¿Olvidó su contraseña?") returns "¿Ólvido su contraseña?"

Upvotes: 2

Views: 462

Answers (2)

Botond Balázs
Botond Balázs

Reputation: 2500

The encoding of the generated page (probably UTF-8) is not the same as the encoding of your source code.

You need to compare the <meta charset="..."> tag in the generated HTML and the encoding of your source code (here is a simple way to find it out).

If they are different, the simplest solution is to save your source code with the same encoding as the web page.

If the problem persists, try adding this to your Web.config:

<system.web>
    <globalization fileEncoding="utf-8" />
</system.web>

Upvotes: 1

Lucas Micheleto
Lucas Micheleto

Reputation: 301

There is no difference if you are using just a static content, but if you need retrieve the text from a db or a file for example, this is gonna be useful to display the chars with the correct encoding.

Upvotes: 0

Related Questions