4

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 ?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
TanguyB
  • 1,954
  • 3
  • 21
  • 40

3 Answers3

7

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.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
4

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)
James Ellis-Jones
  • 3,042
  • 21
  • 13
0

I have used the following to get data out of my model into a JS object. Thought I would post to possibly help someone in the future...

var items = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Items));
mouldycurryness
  • 69
  • 1
  • 11