Home > database >  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?

Time:12-20

I have a 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.

I came with this idea that I can render Product into the page and parse it using JSON.parse.

Product.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. Thus the JSON.parse method complains that:

VM27754:1 Uncaught SyntaxError: Unexpected token
in JSON at position 246
at JSON.parse ()
at :1:6

What can I do? How can I escape newline in my serialized JSON? Is there a better way?

CodePudding user response:

I think your code is not match sense. You should process Model in Controller then you sent the Object to View via ViewModel. Everything the View does just display the data. It's not process data. Or if you want to use javascript to fetch some data from the server. I think a API in this case is better. It's my idea. Hope it's helps you something.

Thanks

CodePudding user response:

you have a bug, remove " ' ' " from your code and send a Product instance as a model, and use parse after stringfying

@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

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