Using C# in ASP.NET, I want to take the result of two text fields, add them when a button is pressed, and display the result. However, if one or both of the fields are empty, I don't want any result shown.
Right now I keep getting 0 as the result if both fields are empty. I'm pretty sure this is because the two input numbers (doubles) are being assigned a default 0. How can I check for empty fields?
This is my method in my controller.
[HttpPost]
public ActionResult French(FrenchModel model, string returnUrl)
{
switch (model.operation)
{
case 1:
model.result = model.numberOne + model.numberTwo;
break;
case 2:
model.result = model.numberOne - model.numberTwo;
break;
case 3:
model.result = model.numberOne * model.numberTwo;
break;
case 4:
model.result = model.numberOne / model.numberTwo;
break;
}
return View(model);
}
As an object, it can be assigned a null reference. But "double" (with a lowercase 'd') is a primitive type, so it cannot be assigned a null reference. The analogous primitive value is simply zero.
double is a value type, which means it always needs to have a value. Reference types are the ones which can have null reference. So, you need to use a "magic" value for the double to indicate it's not set (0.0 is the default when youd eclare a double variable, so if that value's ok, use it or some of your own.
Doubles are value types and thus cannot be assigned to null or "empty". If you want this capability, try using a nullable double. Either Nullable<double>
or double?
should work.
Be aware, using a nullable value type you will need to check it for null before you use it or risk a NullReferenceException
whereas double
defaults to 0
if unassigned.
Use Double?
ie nullable Double, its default value is null and you'll assign a value only if textbox is not empty and you can parse it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With