I'm trying to check for multiple errors on my form. Here is the code I have:
var hasErrors = false;
var sb = new StringBuilder();
if (string.IsNullOrEmpty(creditCard.CardNumber))
{
hasErrors = true;
sb.AppendLine("Credit card number is required.");
//ModelState.AddModelError("PaymentAmount", "Credit card number is required.");
}
if (string.IsNullOrEmpty(creditCard.ExpirationDateMonth) || string.IsNullOrEmpty(creditCard.ExpirationDateYear))
{
hasErrors = true;
// ModelState.AddModelError("PaymentAmount", "Expiration date is required.");
sb.AppendLine("Expiration date is required.");
}
if (string.IsNullOrEmpty(creditCard.NameOnCard))
{
hasErrors = true;
// ModelState.AddModelError("PaymentAmount", "Name is required.");
sb.AppendLine("Name is required.");
}
decimal amt = 0;
creditCard.PaymentAmount = creditCard.PaymentAmount.Replace("$", string.Empty);
if (!decimal.TryParse(creditCard.PaymentAmount, out amt))
{
hasErrors = true;
//ModelState.AddModelError("PaymentAmount","Amount is invalid.");
sb.AppendLine("Amount is invalid.");
}
if (hasErrors)
{
ModelState.AddModelError("PaymentAmount", sb.ToString().Replace(Environment.NewLine,"<br>"));
return View("CreditCard", creditCard);
}
I'm trying to get AddModelError
to display in multiple lines but I'm not having any luck. It's displaying the <br>
as text on the screen instead of rending a break.
I had it where the error was being submitted individually but you'd have to submit the form multiple times before you got the errors on screen. That's why the AddModelError
is commented out in each line.
Is there a way to display multiple lines on the AddModelError
or is there a better way to handle this?
Thanks for the help!