Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 : Validation get message list

I have this :

public class Customer
{
    [DisplayName("Lastname"), StringLength(50)]
    [Required(ErrorMessage="My Error Message")]
    [NotEmpty()]
    public override string LastName { get; set; }

    [DisplayName("Firstname"), StringLength(50)]
    [Required(ErrorMessage="My Error Message 2")]
    [NotEmpty()]
    public override string FirstName{ get; set; }
}

In the controller, I do this :

if (!TryValidateModel(myCustomer))
{
  //HERE
  ....
}

Where "HERE" is, I'd like get all error messages.

Some sample cases :

  1. If "LastName" is missing I'd like get "My Error Message"
  2. If both are mising, I'd like get a List (or other) with the values "My Error Message" and "My Error Message 2"

Any idea ?

Thanks,

like image 538
Kris-I Avatar asked Jun 08 '11 07:06

Kris-I


1 Answers

You could get a list of all errors with their respective field and message like this:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();
like image 91
Darin Dimitrov Avatar answered Nov 01 '22 18:11

Darin Dimitrov