Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 model DisplayFormat and JSON

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?

like image 928
M. Ryan Avatar asked Mar 11 '26 14:03

M. Ryan


2 Answers

The call to return Json(myObjects, JsonRequestBehavior.AllowGet) actually returns a JsonResult. The internals of the JsonResult perform a call:

JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));

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 JsonResult that honors the DisplayFormat attribute.

like image 171
Ken Brittain Avatar answered Mar 14 '26 02:03

Ken Brittain


The DataAnnotations namespace attributes will only handle it for dynamic data controls and display formatting. What you'd need to do is just some basic rounding before passing your object to the Json() method. Something like this would suffice:

myObjects.Yearly_act_pct = Math.Round(myObjects.Yearly_act_pct, 2); // provided you wanted to round to nearest two fractional digits
return Json(myObjects, JsonRequestBehavior.AllowGet);

This will give you the "small double" value, but you're still passing a double, not a string that can be a formatted double. Not sure if that makes sense, but a double is a double, and the best you can do is to round it so it doesn't have an excess amount of fractional digits.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!