I'm trying to send a model created using javascript (because it is created manually by the user) to an MVC controller.
The model is quite complex and one class uses the double?
type for a variable. It works fine with int
numbers but when I use "0.5"
the value is set to null.
What is the reason why double value fail and what can I do about it?
Some code:
var serie = {};
serie.Name = $(elem).children("#name").val();
serie.UnitMeasurement = $(elem).children("#unitMeasurement").val();
serie.ThresholdRed = $(elem).children("#redThreshold").val();
serie.ThresholdYellow = $(elem).children("#yellowThreshold").val();
public class Serie
{
public string Name { get; set; }
public string UnitMeasurement { get; set; }
public double? ThresholdRed { get; set; }
public double? ThresholdYellow { get; set; }
}
You can use your class like-
public class Serie
{
public string Name { get; set; }
public string UnitMeasurement { get; set; }
public string ThresholdRed { get; set; }
public string ThresholdYellow { get; set; }
}
and then while using these varriables you can convert them like-
double? d = Convert.ToDouble(ThresholdRed);
or you can use double.TryParse
like-
double d;
bool result = double.TryParse(str, out dbl); // `result` will be the status of tried Parsing (true or false)
In order to avoid any confusion with culture, encode your parameters before sending like-
var serie = {};
serie.Name = escape($(elem).children("#name").val());
serie.UnitMeasurement = escape($(elem).children("#unitMeasurement").val());
serie.ThresholdRed = escape($(elem).children("#redThreshold").val());
serie.ThresholdYellow = escape($(elem).children("#yellowThreshold").val());
While using them on server, decode them first-
double? d = Convert.ToDouble(HttpUtility.HtmlDecode(ThresholdRed));