简体   繁体   中英

Unicode conversion from C# to javascript

I have an issue that´s giving me many problems. I need to set from an cshtml using C# code some variables to javascript. The problem is that accutes and the spanish "ñ" are showed like unicode strings in the window.

I´m trying this code:

@:var nombrePersona = '@System.Text.Encoding.Unicode.GetString(System.Text.Encoding.Unicode.GetBytes(participante.Nombre))'
@:var apellidoPersona = '@System.Text.Encoding.Unicode.GetString(System.Text.Encoding.Unicode.GetBytes(participante.Apellidos))'

And the result in javascript is like:

"Jes'&'#250;s" and it should be "Jesús"

Any idea of how to fix this?

Thank you

Try this:

var nombrePersona = '@Html.Raw(HttpUtility.HtmlDecode(participante.Nombre))'
var apellidoPersona = '@Html.Raw(HttpUtility.HtmlDecode(participante.Apellido))'

EDIT

Also. If you fill HtmlDecode() with a badly formatted string, it won't work. Try cleaning it first:

"Jes'&'#250;s".Replace("'", "")  // "Jesús" 

You can try this:

var nombrePersona = '@Html.Raw(HttpUtility.JavaScriptStringEncode(participante.Nombre))'
var apellidoPersona = '@Html.Raw(HttpUtility.JavaScriptStringEncode(participante.Apellido))'

Saludos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM