Convert a C# Object to JavaScript in MVC Razor

Update:  Find more of these tips and tricks in our Foundations of Sitefinity 5.1 class, where you'll learn how to use JavaScript, KendoUI and ASP.NET MVC + Razor in Telerik's Sitefinity CMS. Sign up for Foundations of Sitefinity 5.1.

 Creating a JavaScript application on top of ASP.NET MVC is becoming more common these days. Rightfully so, especially with the new Web API addition to MVC 4. The clear separation between client-side and server-side is an elegant architecture indeed!

Retrieving collections and objects from MVC is simply a matter of calling the REST URL via AJAX. The result will give you a serialized JSON object that JavaScript adores. This is great for interactions from the user. What about the case of initializing your JavaScript application? Back in the days, we would use an .INI file to store our application configurations. Now with JavaScript, we would like those configurations provided in JSON form. However, waiting for your AJAX to get the initialization values from the server is precious time wasted. There is a better way...

It would be natural to think of outputing a JSON object onto the page from server-side. That way, when the page loads, the JSON object is rendered to a JavaScript variable and ready to use instantly. Take the following example in which I would like to convert the C# object into JavaScript.

My C# object looks like this:

public class MyConfigObject
{
    public string MyPropA { get; set; }
    public string MyPropB { get; set; }
    public string MyPropC { get; set; }
 
    public MyConfigObject()
    {
        MyPropA = ConfigurationManager.AppSettings["SomeValue1"];
        MyPropB = ConfigurationManager.AppSettings["SomeValue2"];
        MyPropC = ConfigurationManager.AppSettings["SomeValue3"];
    }
}

I would like to render this to JavaScript on the Razor template so my client-side application can use the values to initialize itself immediately without calling any web service. I would first be inclined to create the object manually in Razor like below:

<script type="text/javascript">
    MyNamespace.myConfig = {
        MyPropA: @ConfigurationManager.AppSettings["SomeValue1"],
        MyPropB: @ConfigurationManager.AppSettings["SomeValue2"],
        MyPropC: @ConfigurationManager.AppSettings["SomeValue3"]
    }
</script>

However, this is a sloppy approach because anytime I extend or change MyConfigObject in C#, this means I have to go back into my JavaScript object and update it. So how do I dynamically render the object into JavaScript?... Are you ready for the magic line you have been waiting for? Here it goes:

<script type="text/javascript">
    MyNamespace.myConfig = @Html.Raw(Json.Encode(new MyConfigObject()));
</script>

The Json.Encode will serialize the initialized object to JSON format. Then the Html.Raw will prevent it from encoding the quotes to &quot;. This will render to:

<script type="text/javascript">
    MyNamespace.myConfig = {
        "MyPropA": "abc",
        "MyPropB": "lmn",
        "MyPropC": "xyz"
    }
</script>

Nice huh? MVC, Razor, and JavaScript continue to work in perfect harmony.

Happy Coding! :)
comments powered by Disqus