Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  148] [ 3]  / answers: 1 / hits: 45207  / 9 Years ago, fri, october 2, 2015, 12:00:00

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?.
}

More From » c#

 Answers
84

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


[#64858] Thursday, October 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
khalilb

Total Points: 173
Total Questions: 110
Total Answers: 105

Location: Honduras
Member since Thu, Mar 23, 2023
1 Year ago
;