tags:

views:

140

answers:

1

Are there any issues with using anonymous types with the Json() method in asp.net mvc?

I recently had an issue where returning an anonymous type from a Linq .First() would not work when returned to the jQuery caller. I created a simply subclass inside my controller and simple assigned values from the query object and that seemed to serialize and work fine.

This worked:

public class JsonJob
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public DateTime? DateModified { get; set; }
};

var jsonJob = from job in db.Jobs
              where job.Id == jobId
              select new JsonJob
              {
                  Id = job.Id,
                  Title = job.Title,
                  Description = job.Description,
                  DateAdded = job.DateAdded,
                  DateModified = job.DateModified
              };

return Json(jsonJob.First());

But this did not:

var jsonJob = from job in db.Jobs
              where job.Id == jobId
              select job;

return Json(jsonJob.First());
+1  A: 

Your second query does not return an anonymous type. It probably returns an entity type (generated by the DataContext code generator from the DBML file), which might have a bunch of things you don't like. Returning an anonymous type shouldn't cause a problem as the Json method doesn't care about the type name at all:

// anonymous type example:
var jsonJob = from job in db.Jobs
              where job.Id == jobId
              select new {  // Note that no class name is specified here 
                 job.Id,
                 job.Title, 
                 job.Description, 
                 job.DateAdded, 
                 job.DateModified
              };
Mehrdad Afshari
If I do a 'select new { Id = job.Id, Title = job.Title };' the end result is the same. Using an actual defined type seems to work.
James
James: What's the end result?
Mehrdad Afshari
Success callback from the page is never called. So something is making $.getJSON freak out.
James
James: I'm sure `Json` doesn't care about the type name. I just tested it with a simple anonymous type and it worked as I expected. Changing `select new JsonJob {` to `select new {` should not change anything as far as `Json` method is concerned. The problem is probably somewhere else.
Mehrdad Afshari