Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to filter domain objects for json output in an ASP.NET MVC application

If I'm rendering a regular view in asp.net mvc the only domain object properties that show up in my page the ones I specifically write out. For example:

<div><%= Customer.FirstName %></div>

However, if I serialize a domain object for json it will include every property. Example:

public JsonResult Customer (int? id)
{
    Customer customer = _serviceLayer.GetCustomer (id.Value);

    return Json (customer);
}

Since I don't want every Customer property exposed what is the best way to filter the output properties for json in this case? Can you use an include/exclude list like UpdateModel()? Use a proxy class such as public class JsonCustomer? What would you recommend?

like image 899
Todd Smith Avatar asked Dec 16 '08 22:12

Todd Smith


2 Answers

I use anonymous types for this:

var customer = from c in serviceLayer.GetCustomers()
               where c.Id == id.Value
               select new { FirstName = c.FirstName };

This is not just a good idea. Rather, it's protection against the exception that you will get when calling Json() if your object graph contains a circular reference.

like image 138
Craig Stuntz Avatar answered Sep 20 '22 05:09

Craig Stuntz


You may use the [ScriptIgnore] attribute (in System.Web.Extensions). See http://www.creave.dk/post/2009/10/07/Excluding-properties-from-being-serialized-in-ASPNET-MVC-JsonResult.aspx for an example.

like image 27
JacobE Avatar answered Sep 21 '22 05:09

JacobE