Convert a C# Object to JavaScript in MVC Razor

By May 16, 2012 MVC No Comments

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! :)

The following two tabs change content below.

Basem Emara

Software Architect at Falafel Software
Basem has over 10 years experience as a consultant and developer for dozens of projects for educational, advocacy, non-profit, small business, enterprise, and governmental organizations. As an innovator who recognizes and leverages the power of the web, he has been able to help real estate agencies, schools, hospitals, wholesale distributors, shipping carriers, and other businesses pioneer their industries utilizing the best that today’s technology has to offer from a more creative point of view. Simple yet elegant is the key to his approach, as well as the belief that continual process improvement is always possible.