ASP.NET MVC 3: checking for a message list

I have it:

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", I would like to receive all error messages.

Some examples:

  • If "LastName" is missing, I would like to receive a " My Error Message "
  • If they both change, I would like to get a list (or another) with the values My error message "and" My error message 2 "

Any idea?

Thank,

+5
source share
1 answer

You can get a list of all errors with the appropriate field and message like this:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();
+13
source

All Articles