Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!