Johncl
Johncl

Reputation: 1231

How to get a dynamically created Json data set in MVC 3 controller?

Ok, so I am using MVC 3 and it is great at de-serializing a JSON data set into a strongly typed object that is passed to my controller action. Unfortunately I have not found a solution to a more dynamic case.

Does the built in Json de-serialisation and classes have support for an "undefined" property set? For example lets say I have some fixed data like name and age, but I also want to pass down a dynamically created rating list where the user could enter (or select) a movie and set a rating value in a table.

The model data structure could be something like this:

public class UserRatings
{
  public string Name { get; set; }
  public int Age { get; set; }
  public Dictionary<string,int> Ratings { get; set; }
}

But assuming that my Json dataset looks like this from javascript:

var data = { Name: name, Age: age, Ratings: rating };

Where the rating variable is a dynamically constructed object that consist of the name (or id) of of the movie as key and rating as number. Naturally de-serialization of this in the controller action will not be successful as it does not understand the mapping of Ratings to the rather complex dictionary object. But is there a generic Json collection that I could use instead for Ratings as an intermediate format?

I have tried making the Ratings object a Json string in javascript and just sending a string down, but I am unable to find a "factory" or something that can make a Json structure in C# that I can iterate over to get the data out. The classes Json and JsonResult does not help me in this regard it seems. Basically how can I use the built in Json support in MVC to do my own de-serialisation into some generic Json collection object?

Upvotes: 2

Views: 3175

Answers (3)

DalSoft
DalSoft

Reputation: 11127

See my answer Passing dynamic json object to C# MVC controller basically using a dynamic type and a ValueProviderFactory is the cleanest way to deserialize Json to something more dynamic.

Upvotes: 1

Whimsical
Whimsical

Reputation: 6355

There's another option which i prefer using for being neater...(we eliminate the step of getting data from the request stream)

Here's a code sample

Cat catObj = new Cat();

if (TryUpdateModel<Cat>(catObj))
{
//do stuff
}
else
{
//invalid input
}

The TryUpdateModel resides in the controller namespace and hence no need to add any additional reference.

If you just need the Json sent in as part of the request you could obtain it using the following block of code(you could also obtain it from Request.Form)

using (StreamReader reader = new StreamReader(Request.InputStream))
{
    var inputJson = reader.ReadToEnd();
}

Upvotes: 0

archil
archil

Reputation: 39501

You Could Use JavaScriptSerializer or DataContractSerializer with Some ActionFilters. They're very flexible

Upvotes: 4

Related Questions