Reputation: 560
I'm stuck on a problem I can't seem to solve. On the back-end I'm using ASP.NET Core 2.0, from a Controller to a View using ViewBag sending an array containing a couple of words. E.g. "These", "Are", "Överdrivna", "Påse".
Using the following Razor code in my view i loop out the results
@foreach (var words in ViewBag.Words)
{
<span>@words.word</span>
}
However i want to send the contents of this array into a JavaScript array and this is where the trouble starts. E.g. if I do this:
<script>
console.log("åäö"); <-- this works
@foreach (var words in ViewBag.Words)
{
console.log('@words.word');
}
</script>
The words without nordic characters show up correctly in the console, e.g. "These". However when the word/words with "ÅÄÖ" are to be printed out I get them printed out as "påse"
instead of "påse".
All my views and files are saved as UTF-8 (double checked with both Visual Studio and Notepad++). And as stated above, it prints out just fine when not using JavaScript.
What could I be doing wrong, and how can i fix it?
Thanks in advance!
Upvotes: 3
Views: 120
Reputation: 573
Use the Javascript Encoder;
Add the reference for Encodings:
@using System.Text.Encodings.Web
And then:
@foreach (var words in ViewBag.Words)
{
@: console.log("@JavaScriptEncoder.Default.Encode(@words)");
}
Upvotes: 1