Push C# (Razor) objects to JavaScript array of objects

If you wonder, how to push C# objects to a JavaScript array in ASP.NET View using Razor, you came to the right place. 🙂 In this post I will tell you, how I achieved it.

Lets say I have a collection List<Category>. Object Category consists of parameters id, category name and list of subcategories (also of type Category):

public class Category {
  public int Id { get; set; }

  public string Name { get; set; }

  public List<Category> Subcategories { get; set; }
}

List<Category> is also my strongly typed View’s Model. My goal is to achieve Javascript array like this: [{“id”:…, “name”:”…”, “subcategories”:[{“id”:…, “name”:”…”}]},{…}]. In order to create objects like that, I must firstly create collection of anonymous objects and serialize it to string.

@{
  //serializer initialization
  System.Web.Script.JavascriptSerializer js = new System.Web.Script.JavascriptSerializer();

  var data = Model.Select(c => new {
    id = c.Id,
    name = c.Name,
      subcategories = c.Subcategories.Select(cc => new {
      id = cc.Id,
      name = cc.Name
    })
  });

  //serialize collection of anonymous objects
  string arrStr = js.Serialize(data);
}

Now I have to inject this string to JavaScript:

var categories = JSON.parse('@arrStr'.replace(/&quot;/g, '"'));

As you can see, I injected string using Razor. I also used replace function in order to replace all &quot; occurances with " (double quotes).

Warning: JavaScript replace function replaces only first occurrance of searched pattern. In order to replace all occurrances I had to use regular expression with flag g, which is used to perform a global match.

The last thing to do is to call JSON.parse, which converts properly processed string into JavaScript object. Now we have JavaScript array of desired objects, which can be used further in our JavaScript functions/events.