简体   繁体   中英

Parsing in C# MVC asp.net Model

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();    
  }              
}

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.

Does this help?

decimal number;

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

var value = "1,643.57";

Decimal.TryParse(value, out number);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM