I’m building an app using ASP.NET Core 8.0 MVC.
In the code shown here, in my view, the French accented characters are not showing well (see 1st screenshot):
@model List<ViewListTable>
<head>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<script type="text/javascript">
function f() {
var myArray = [];
@foreach (var d in Model)
{
@:myArray.push("@d.Name");
@:console.log("@d.Name");
}
var cptData = myArray.length;
var tableau = document.getElementById('tableau');
var tbl = document.createElement("table");
var x = 0;
for (var i = 0; i < cptData / 3; i++) {
var tr = document.createElement('tr');
for (j = 0; j < 3; j++) {
var td = document.createElement('td');
if (x < cptData) {
var a = document.createElement('a');
var el_span = document.createElement('span');
var linkText = document.createTextNode(myArray[x]);
var tab = myArray[x];
el_span.setAttribute('style', 'color: #07C');
a.setAttribute('href', "'" + tab + "'");
a.setAttribute('class', 'button');
a.title = "Éditer les données de la table:";
a.appendChild(linkText);
el_span.appendChild(a);
td.appendChild(el_span);
};
x += 1;
tr.appendChild(td)
};
tbl.appendChild(tr);
}
tableau.appendChild(tbl);
}
</script>
</head>
<body>
<div id="tableau"></div>
<script>
f();
</script>
</body>
But the tag meta charset=”utf-8″ is set in my _layout file. I have tested the 2nd code in the same file and in the contrary it works fine (see 2nd screenshot) in the same file:
@model List<ViewListTable>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</head>
<body>
<div class="container">
<div class="col-6">
Liste des tables
</div>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th class="col-6">
Nom des tables de la BD
</th>
</tr>
</thead>
<tbody>
@foreach (var obj in Model)
{
<tr>
<td>@obj.Name</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
When inserting French accented characters into JavaScript code, it is important to handle quotation marks and other special characters correctly, and they need to be escaped to ensure the correctness and security of the string.
So, I did the escaping process by changing this code
@:myArray.push("@d.Name");
@:console.log("@d.Name");
to
@:myArray.push("@Html.Raw(d.Name.Replace(""", "\"").Replace("'", "\'"))");
@:console.log("@Html.Raw(d.Name.Replace(""", "\"").Replace("'", "\'"))");
Then it worked, and the test result changed from:
to
0