0

Homework hands-on assignment.

I have a model that spits out a simple addition form in an html page. The view model is written to handle Required Values (for instance: [Required(ErrorMessage = "Missing a number, please enter decimals to add.")]

However, in the Domain model, I need to TryParse the two input fields to verify that the values entered are decimal values (either positive or negative). I have attempted to filter based on [Range], a simple TryParse, Parse, and every other thing I know how to do but cannot get around the exceptions to actually see an error message (like the above "Missing a number, please enter decimals to add"). I have searched on this and many other sites including:

and more... Any help would be greatly appreciated.

public class MyAbacusDomainModel
{
  public MyAbacusDomainModel(string number1, string number2)
  {
    Number1 = number1;
    Number2 = number2;
    Sum = CalculateSum(number1, Number2);
  }

  public string Sum { get; set; }
  public string Number1 { get; set; }
  public string Number2 { get; set; }

  // need to parse the two number values here to get the boolean results

  private string CalculateSum(string number1, string number2)
  {
    double number1double = Convert.ToDouble(number1);
    double number2double = Convert.ToDouble(number2);
    double sum = (number1double + number2double);
    return sum.ToString();    
  }              
}
Community
  • 1
  • 1
R. Call
  • 1
  • 1
  • 5
    Can you explain why do you store a number inside a string? Why don't you simply declare your Number1/2 as double/decimal? – Steve Feb 07 '17 at 20:49
  • Maybe using `contracts`? – Hackerman Feb 07 '17 at 20:50
  • Assignment had a code snippet that was string (with only numbers), Instructor gave no instructions so I am converting it to double but still trying to get past the exceptions. – R. Call Feb 07 '17 at 21:12

2 Answers2

1

You can make a viewmodel property as double? type with Required and Range attribute.

You will not need to check wheter values are double because they will be always good values if ModelState.IsValid is true in controller's action.

[Required]
public double? Number {get; set;}

If there is some kind of necessity to use string values in your domain model then you can just parse your input to string. It will be always double value so you do not need to make any additional checks.

If there is not such requirement for your homework then it would be advisable to change types which stores values for your domain model. It's uncommon and wrong to store numbers as strings.

Shoter
  • 651
  • 8
  • 17
0

Does this help?

decimal number;

// Parse a floating-point value with a thousands separator.

var value = "1,643.57";

Decimal.TryParse(value, out number);
Teja
  • 220
  • 1
  • 6