I have a number input, and when the user enters a number, it will be sent from the view to the controller using Ajax. Everything works fine, but when the user enters decimal numbers, I get binding errors (1,1 or 1.2 etc). I want the user to be able to use decimal numbers.
This is the relevant View code:
var postdata = {x: <number input value>};
$.ajax({url: url, type: "POST", data: postdata, async: false})
This is the Controller function:
[HttpPost]
public ActionResult MyFunction(decimal x)
{
return Json(new {success = true, JsonRequestBehavior.AllowGet});
}
You need to stringify you data when you are sending decimal values.
data: JSON.stringify({ x: 5.0 })
This is because the decimal is considered an integer by the default binder.
Please have a look on lelow link for more information :-
C# MVC Controller cannot get decimal or double values from Ajax POST request
Edit 1:-
You can also try :-
parseFloat(value).toFixed(2)
just send the value as it is and try to convert in controller instead
var postdata = {x: $("#input").val()};
$.ajax({url: url, type: "POST", data: postdata, async: false})
This is the Controller function:
[HttpPost]
public ActionResult MyFunction(string x)
{
double z=Convert.ToDouble(x.Trim()); // trim just in case....
return Json(new {success = true, JsonRequestBehavior.AllowGet});
}
In case of your double try this it should work (replacing . with ,)
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
I ran into the same issue, with a double (not a decimal), but I think the solution might be the same. For me it was all about culture and setting the right number format!
Solution:
NumberFormat = NumberFormatInfo.InvariantInfo;
This is a parameter of the CultureInfo
of the app! You can set this in multiple places. If there is only one culture on your app, set this on Application_Start()
on Global.asax
.
No changes on Web.config and works with $("#input").val()
(with or without parseFloat()
).
It's actually quite simple:
Model:
public decimalValue
In Ajax data:
$("#value").val().replace(",",".")
It will automatically send the value to the Controller.
(10.90, 10.90)
Declaring the Input
as a number helps not to give an error, if you send a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.