简体   繁体   English

How to send a C# object to the browser to have it as a JavaScript JSON object?

[英]How to send a C# object to the browser to have it as a JavaScript JSON object?

I have a Product class.我有一个Product class。 I have an instance of it.我有一个例子。 I want to have access to it both in my Razor page and in my browser JavaScript.我想在我的 Razor 页面和浏览器 JavaScript 中都可以访问它。

I came with this idea that I can render Product into the page and parse it using JSON.parse .我的想法是,我可以将Product渲染到页面中并使用JSON.parse对其进行解析。

Product.cshtml:产品.cshtml:

@{
    var options = new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
    };
}
<script>
    var productJson = '@Html.Raw(JsonSerializer.Serialize(product, options))`;

    var product = JSON.parse(productJson); // here I encounter error
</script>

But my product has a field called Description and inside it I have new lines.但是我的产品有一个名为Description的字段,在其中我有新的行。 Thus the JSON.parse method complains that:因此JSON.parse方法抱怨:

VM27754:1 Uncaught SyntaxError: Unexpected token VM27754:1 未捕获的语法错误:意外的令牌
in JSON at position 246在 JSON 在 position 246
at JSON.parse ()在 JSON.parse ()
at:1:6在:1:6

What can I do?我能做些什么? How can I escape newline in my serialized JSON?如何在我的序列化 JSON 中转义换行符? Is there a better way?有没有更好的办法?

I think your code is not match sense.我认为您的代码不匹配。 You should process Model in Controller then you sent the Object to View via ViewModel.您应该在 Controller 中处理 Model 然后通过 ViewModel 将 Object 发送到 View。 Everything the View does just display the data. View 所做的一切都只是显示数据。 It's not process data.这不是过程数据。 Or if you want to use javascript to fetch some data from the server.或者,如果您想使用 javascript 从服务器获取一些数据。 I think a API in this case is better.我认为在这种情况下 API 更好。 It's my idea.这是我的主意。 Hope it's helps you something.希望它对你有所帮助。

you have a bug, remove " ' ' " from your code and send a Product instance as a model, and use parse after stringfying你有一个错误,从你的代码中删除“''”并将 Product 实例作为 model 发送,并在 stringfying 后使用 parse

@using System.Text.Json
@model Product

@{
   
    var options = new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
    };
}
<script>

    var model = @Html.Raw(JsonSerializer.Serialize(@Model, @options));
 
  var product =JSON.parse(JSON.stringify(model));

  var productName=product.name; //or product["name"]

</script>

or instead of Text.Json you can use a standard javascript serializer as well或者代替 Text.Json 您也可以使用标准 javascript 序列化程序

   var model = @Html.Raw(Json.Serialize(@Model));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM