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 ""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 ?

2
  • @CamiloTerevinto doing this gives me the type of the model in the data part. Commented Jan 2, 2018 at 12:11
  • Please reopen this question. There's a better way to do this in ASP.NET Core (not available in the duplicate) Commented Jan 2, 2018 at 12:16

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@ChristianGollhardt What? The question is how to serialize JSON so that it can be used in javascript
Ah my bad, didn't noticed the IJsonHelper.
5

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.