最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - .NET Core Object JSON Serialization to Javascript format - Stack Overflow

programmeradmin4浏览0评论

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 ?

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 ?

Share Improve this question edited Jan 2, 2018 at 12:15 Camilo Terevinto 32.1k7 gold badges94 silver badges126 bronze badges asked Jan 2, 2018 at 12:04 TanguyBTanguyB 2,0065 gold badges25 silver badges41 bronze badges 2
  • @CamiloTerevinto doing this gives me the type of the model in the data part. – TanguyB 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) – Camilo Terevinto Commented Jan 2, 2018 at 12:16
Add a ment  | 

3 Answers 3

Reset to default 8

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)

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));
发布评论

评论列表(0)

  1. 暂无评论