C# MVC Controller cannot get decimal or double values from Ajax POST request
My problem is that when I try to send a double or decimal via ajax into my C# MVC Controller the value is always null. I can send the value as string and I can send Integers without a problem. Why can't I send values with decimals? When I check the request that is sent from the client the correct value is there (Form Data is price=84.50
).
Error:
The parameters dictionary contains a null entry for parameter 'price' of non-nullable type 'System.Decimal'
Html:
<input type="number" step="1" class="form-control" name="price" id="price">
<button type="button" class="btn btn-success">Send</button>
Javascript:
$('.btn-success').click(function () {
//var price = $('#price').val(); - Did not work
//var price = Number($('#price').val()); Did not work
var price = Number($('#price').val()).toFixed(2); // Does not work
$.ajax({
url: 'PriceFunction',
type: 'POST',
data: {
price: price,
}
}).done(function () {
}).fail(function () {
console.log("Error in ajaxfunction!");
});
});
C#:
[HttpPost]
public void PriceFunction(decimal price)
{
// I have tried with decimal, double and double?.
}
You need to stringify you data when you are sending decimal values.
data: JSON.stringify({ Price: 5.0 })
This is because the decimal is considered an integer by the default binder.
You could of course change to using the DecimalModelBinder
which is detailed at the following link:
ASP.NET MVC3 JSON decimal binding woes
This could be a Culture issue
Be sure that the string you are sending to your action is compliant to the current Culture. (check the decimal number separators .
,
)
Exemple
e.g. on a french server, 99.1
will not be understood as 99,1
, but will be converted to 0
.
Solution
In that case, one solution is to define culture in your Web.Config
<system.web>
...
<globalization uiCulture="en" culture="en-US"/>
</system.web>
Or, replacing the separator by the proper one on the client side.