0

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});
}
Pelle
  • 741
  • 1
  • 9
  • 16

4 Answers4

0

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)
Community
  • 1
  • 1
Anand Systematix
  • 632
  • 5
  • 15
0

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);
Dandy
  • 467
  • 1
  • 10
  • 33
  • I am not able to use var as a parameter type. As far as I know, the compiler won't be able to deduce the type. Atleast I get an error. – Pelle Feb 15 '17 at 10:12
  • i have tried with double.Parse() it working you just need to replace "," with "." – Dandy Feb 15 '17 at 10:27
0

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()).

Miguel Rebocho
  • 179
  • 2
  • 10
0

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.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77