JSON and .NET Decimals
I recently had a problem with my controller inconsistently picking up a decimal value in my model. Here’s what the Action looked like:
[HttpPost]
public ActionResult SaveItem(Item myItem) {...}
For simplicity we’ll say this is what Item looked like:
[DataContract]
public class Item { [DataMember] public long Id { get; set; }
[DataMember] public decimal Speed { get; set; } }
I JSON.stringify()’d the object on the client side and got this as the data for my Ajax call:
"{"myItem":{"Id": 10, "Speed": 5}}"
Looks good, right? Except…JavaScript sees that the Speed is just “5” (it’s weakly typed, so it interprets that as an integer). When .NET tries to cast that as a decimal it chokes and just returns “0”. So, if your values don’t have anything following the decimal, you’re screwed.
Phil Haack has a solid workaround that changes the model binding for MVC, but a really simple workaround is to force your property to be a decimal using JavaScript’s “.toFixed(x)” function. Call “this.Speed.toFixed(2)” to get a string with two places after the decimal (“5.00” in our example). Just perfect for your JSON and .NET project! Here’s the resulting JSON string:
"{"myItem":{"Id": 10, "Speed": "5.00"}}"