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?
I use anonymous types for this:
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.