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

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.


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.


Please use a view model. A view model is an object that the UI uses to represent your domain objects on the screen. Each screen has its own view model.

When you make your view model, which is a DTO, which is a flattened, null-safe projection of domain objects, do not map properties you do not wish to be displayed on the screen.

Serialize the view model, not your domain object.