mohsinali1317
mohsinali1317

Reputation: 4425

Special Characters turn to html code C#

In my web app, I am sending some strings from the server, and I am using them like this in my JS

var Texts = {
    FillAllFieldsError: '@Texts.FillAllFieldsError',
    PasswordChangeSuccess: '@Texts.PasswordChangeSuccess'
}

The strings which are coming from the server have some special characters like "Ø,Æ" etc.. They turn up into something with HTML code "forespørsel".

Does anybody know how to solve it? I am using utf-8 encoding

<meta charset="utf-8" />

Upvotes: 1

Views: 1373

Answers (4)

Jeremy Bell
Jeremy Bell

Reputation: 718

This would be the safest way to do what you are trying to do:

var Texts = @Html.Raw(JsonConvert.SerializeObject(new {
   Texts.FillAllFieldsError,
   Texts.PasswordChangeSuccess
});

^ use an anon object if you need to specify which properties to include

Or use an extension method like:

using Newtonsoft.Json;

public static class JavascriptExtensions {
   public static IHtmlString AsJavascript<T>(this T value) where T: class{
      return MvcHtmlString.Create(JsonConvert.SerializeObject(value));
   }
}

Then in your view you could do this:

var Texts @Texts.AsJavascript();

Upvotes: 0

Georgi Karadzhov
Georgi Karadzhov

Reputation: 771

Using @Html.Raw() is the correct approach.

Upvotes: 2

mohsinali1317
mohsinali1317

Reputation: 4425

I used this

@Html.Raw(Json.Encode(Texts.FillAllFieldsError))

and it worked.

Upvotes: 1

NLindbom
NLindbom

Reputation: 508

Include System.Web in your project to use HttpUtility.HtmlDecode(MSDN) to decode HTML-encoded strings.

Upvotes: 1

Related Questions