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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With