5

I have the following .Net class:

public class Product
{
    public int ID {get;set;}
    public String Name {get;set;}
    public Decimal Price {get;set;}
}

And an action in my controller:

[HttpPost]
public ActionResult AddProduct(Product product)
{
       // product.Price is zero!!
}

The JSON string posted in the request to AddProduct looks like this (grabbed through Fiddler2):

POST http://localhost:59656/Cart/AddProduct HTTP/1.1
Host: localhost:59656
Origin: http://localhost:59656
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko Chrome/17.0.963.79 Safari/535.11
Content-Type: application/json; charset=UTF-8
Accept: text/html, */*; q=0.01

{"Product":{"ID":1232, "Name":"Blu-Ray","Price":210}}

Why is product.Price zero while other properties (ID and Name) get hydrated correctly?

Diego
  • 18,035
  • 5
  • 62
  • 66
  • Check the Request.Form collection, look for entry of "Price" and see what the value supplied is. – Brian Mains Mar 28 '12 at 20:30
  • 4
    See http://stackoverflow.com/questions/5698984/default-asp-net-mvc-3-model-binder-doesnt-bind-decimal-propeties. – DMulligan Mar 28 '12 at 20:40
  • That collection is empty. The request is not url-encoded, is JSon encoded. I posted HTTP headers too so this is clear. – Diego Mar 28 '12 at 20:44

1 Answers1

2

Try posting: {"Product":{"ID":1232, "Name":"Blu-Ray","Price":210.00}}

I think MVC doesn't cast/convert from int to decimal so the .00 tells it to hydrate using float/double/decimal.

Alex Moore
  • 3,415
  • 1
  • 23
  • 39
  • Beh. Stupid Microsoft. I decided to switch my variables to the long data type, but it's essentially the same fix. Thanks, Alex! – Chris Jaynes Apr 26 '12 at 21:44
  • 1
    @ChrisJaynes see Phil Haacks blog post for a better fix. http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx – Nathan Koop Aug 03 '12 at 15:22
  • 1
    This is not meant to be snarky, but how is writing a big binding function a better fix than just switching the data type to long? Am I risking some other strange behavior by just using a long? – Chris Jaynes Aug 03 '12 at 16:27