I have a model which has some double properties on it, and with them come a DisplayFormat which converts the double into a nice readable percent.. example
[DisplayFormat(DataFormatString = "{0:P2}")]
public Nullable<double> Yearly_act_pct { get; set; }
This works fine in HTML partials where I wrap the call in
@Html.DisplayFor(modelItem => item.Yearly_act_pct)
However, when I dump some of these objects into a JSON feed, the DisplayFormats seem to be ignored, so I end up with raw decimals, and often big ones.
How can I make this
return Json(myObjects, JsonRequestBehavior.AllowGet);
respect the DisplayFormats?
The call to
return Json(myObjects, JsonRequestBehavior.AllowGet)actually returns aJsonResult. The internals of theJsonResultperform a call:If you look at MSDN for JavascriptSerializer you will there is a simple conversion. This implementation does not appear to honor DisplayFormat.
You can write a class derived from
JsonResultthat honors the DisplayFormat attribute.