views:

35

answers:

2

I have some data that I want to pass into the View (.aspx page) in JSON format.

I could add an async ajax call and load it that way, but since I have the data upfront, why not just dump it into the view.

I could pass a C# object as the model and in Javascript manually iterate through it to fill out a Javascript object, but this seems like something someone has done before and there may well be a tool to do it already...

Thanks in advance, Chris

+2  A: 

You could convert the data into the JSON using Json.net and then pass the Json.net object to the view model as a string.

viewModel.JsonToUse = JsonConvert.SerializeObject(object).ToString();
// Or build the Json up manually using a JOBject.

return View("ViewName", viewModel);
Castrohenge
+1  A: 

You could serialise it using System.Web.Script.Serialization.JavaScriptSerializer.

ViewData["JSONData"] = new JavaScriptSerializer().Serialize(myObject);

You could then render this into a hidden field or wherever on the view.

David Neale
Perfect, thanks for that.
Chris Kimpton