TanguyB
TanguyB

Reputation: 2006

.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 ""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:

error

Some formatting options I forget to set ?

Upvotes: 4

Views: 8806

Answers (3)

mouldycurryness
mouldycurryness

Reputation: 69

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));

Upvotes: 0

Camilo Terevinto
Camilo Terevinto

Reputation: 32088

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.

Upvotes: 8

James Ellis-Jones
James Ellis-Jones

Reputation: 3092

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)

Upvotes: 5

Related Questions