0

I am creating a report which requires returning Lists, and Json data to a web page. I'm working with a multi-tiered application. The web project is created using MVC but the heavy lifting is done in class libraries in separate projects.

I am returning a report object to my controller from a class library but I wanted to know is it possible to return a mix of Lists and Json in the model? Ideally I would like the report model to be similar to the following:

public class Report
{
    public List<TopSellers> TopSellers { get; set; }
    public List<MonthlySales> MonthlySales { get; set; }
    public Json ShopSales { get; set; }

}

This way, the list stuff can be rendered as normal, but the jQuery could grab the Json being return to render the graphs I'm using.

Is this possible?

I have tried to declare it similar to this however the only option I get is 'JsonReaderWriterFactory'.

My exposure of Json up until now has been null so if someone could help me out, or point me in the right direction I'd be very grateful!

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
109221793
  • 16,477
  • 38
  • 108
  • 160
  • 2
    JSON is a text format - can't you return a string? – Oded May 09 '12 at 09:01
  • Hi Oded, thanks for the comment. I could. Would it need to be converted to Json format before passing through to the jQuery? – 109221793 May 09 '12 at 09:05
  • This is a bad idea. JSON is for communicating between systems, not between different parts of the same system – James L May 09 '12 at 09:07
  • If you produce it in JSON to begin with, why convert again? – Oded May 09 '12 at 09:07
  • @ Oded, like I said, very new to this whole thing ;-) Do you think omething like this would work? - http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx – 109221793 May 09 '12 at 09:51

2 Answers2

6

You could use the JSON.net library to serialize your object to a json string and set it to your ShopSales property.

http://json.codeplex.com/

report.OriginalList = objectToSerialize;

var jsonStr = JsonConvert.Serialize(objectToSerialize);
report.ShopSales = jsonStr;

return report; 

On the client you can use the ShopSales property with jQuery.

Rob Angelier
  • 2,335
  • 16
  • 29
1

The only approach I see here (and which I have also adopted once) is to create an HTTP Handler in your class library which intercepts certain requests and directly writes JSON onto the response (JSON.net is worth taking a look at).

Instead of the HTTP Handler you could also take a look on whether you could directly leverage the build-in ASP.net routing mechanism.

Your class library has then to be added as reference to a front-end project (i.e. ASP.net MVC / WebForms) obviously and the handler has to be registered there.

Juri
  • 32,424
  • 20
  • 102
  • 136