Passing serialized C# object in JSON to Razor Page

alexruzenhack

Alex Ruzenhack

Posted on August 24, 2018

Passing serialized C# object in JSON to Razor Page

I was working in a way to convey a dataset coming from the database to Google Chart JavaScript framework, using C# and .NET Core MVC framework under the Razor Page.

The first step was easy, a trivial query to the database in order to get the data, but Google Chart has their special way to handle a dataset and to realize a simple conversion from POCO was not sufficient, then I wrote a converter:

private IEnumerable<Array> poco2GoogleChartDataset(IEnumerable<MyData> dataset)
{
    List<Array> googleDataset = new List<Array>();
    foreach (MyData data in dataset) {
        Array arr = new object[] { data.Label, data.Value };
        googleDataset.Add(arr);
    }
    return googleDataset.ToList();
}
Enter fullscreen mode Exit fullscreen mode

The result of this conversion was serialized to JSON using the Newtonsoft.Json assembly:

// Top of the class
using Newtonsoft.Json;

// Hidden for brevity
ReportJson = JsonConvert.SerializeObject(poco2GoogleChartDataset(myDataset));
Enter fullscreen mode Exit fullscreen mode

On the other hand, in Razor Page, I need to pass this JSON object to a JavaScript variable. If you just pass the model value using a simple Razor syntax, it will not work because in the Razor Render process will pass the value through an HTML encoding. Like this:

// Razor Page
...
@section Scripts {
    function drawChart() {
        var jsonDataset = @Model.ReportJson;
        ...
    }
...
}
Enter fullscreen mode Exit fullscreen mode
jsonDataset result:
[[\&#x22;Label\&#x22;, value]]
Enter fullscreen mode Exit fullscreen mode

To bypass the HTML encoding wrap the model variable into the HtmlHelper directive with their Raw method. This way:

// Razor Page
...
@section Scripts {
    function drawChart() {
        var jsonDataset = @Html.Raw(Model.ReportJson);
        ...
    }
...
}

Enter fullscreen mode Exit fullscreen mode

Now the value result will be a JSON object, ready to be used in Google Chart framework.

I suffered hours to achieve this comprehension, in part because I do not master Razor syntax, nor ASP.NET Core MVC, neither the C# 😂

That's it!

💖 💪 🙅 🚩
alexruzenhack
Alex Ruzenhack

Posted on August 24, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related