views:

53

answers:

2

Hey,

I've got a IList of Sites in my application and Site has a large amount of properties.

I'm wanting to convert this list to JSON to be used in a dropdownlist similar to this

    var sites = SiteRepository.FindAllSites();
    return new JsonResult() { Data = sites, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

the problem I have is that I only want to use the id and name properties of the site class. I was thinking a way round this would be to use an 'adaptor' class that would then only expose these two properties and I would then serialize that.

The problem I have is I want to make the class generic so that it can handle any list of objects. Has anybody come across a similar situation and solved it?

EDIT: I can't use the [ScriptIgnore] Attribute as there may be a case when I do want to serialize the whole class.

A: 

If you decorate you class fields with [ScriptIgnore] (System.Web.Script.Serialization) C# will ignore them during serialization using Json in much the same way that decorating with [XmlIgnore] would for Xml serialization.

MSDN

amelvin
Sorry I should have mentioned this in the question. There may be times when I want to serialize the whole Site class to pass it back via an ajax request
mjmcloug
+3  A: 

Can you create an anonymous class from your list of sites?

var sites = SiteRepository.FindAllSites().Select(x=> new { Id=x.Id, Name=x.Name});

Since FindAllSites() seems to return an IList, which is descended from IEnumberable, you should be able to use System.Linq's extension methods (i.e. Select() ). That'll transform the List<Site> (with all the properties) to IEnumerable<some_anon_class> (with only 2 properties) which is then given to that JsonResult thing instead of the list of Site.

Benny Jobigan
Good solution, but doesn't it need to be: var sites = SiteRepository.FindAllSites().Select(x => new { Id = x.Id, Name = x.Name }); ?
JonoW
Probably. I'll fix it =P
Benny Jobigan
Fricking Genius! thanks!!!!!
mjmcloug
+1 Great solution.
amelvin