Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Object JSON Serialization to Javascript format

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 "&quote;" 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:

error

Some formatting options I forget to set ?

like image 472
TanguyB Avatar asked Jan 04 '23 00:01

TanguyB


2 Answers

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.

like image 98
Camilo Terevinto Avatar answered Jan 05 '23 15:01

Camilo Terevinto


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)
like image 22
James Ellis-Jones Avatar answered Jan 05 '23 13:01

James Ellis-Jones