I've some problems with serializing my C# objects into a plain JSON string.
I user JsonConvert ( Newtonsoft's one) to format a model into a JSON. The problem is that that JSON string get's used in some Javascript, but the format is not good as in a quote gets written down as ""e;" instead of "'". Any idea's on how to fix this ?
//...
@{
var dataJson = JsonConvert.SerializeObject(Model);
}
//...
<script>
function ChangeGroup(type) {
$.ajax({
url: //...,
data: @dataJson
});
}
</script>
what I get is this:
Some formatting options I forget to set ?
There's a much shorter, easier to use and remember in ASP.NET Core:
@Json.Serialize(Model);
When assigned to a JavaScript value, the resulting JavaScript is valid:
<script>
var model = @Json.Serialize(model);
</script>
With this, you don't have to worry about HTML-escaping the characters.
You can do this:
@{
var dataJson = new HtmlString(JsonConvert.SerializeObject(Model));
}
By default ASP.Net Core will HTML encode before rendering an @ expression unless the expression evaluates to a type with the interface IHtmlContent (which HtmlString has). Another way is to write
@Html.Raw(dataJson)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With