How to manually check if model is valid and get the error message
asp.net-mvc
Solution
To Add error for particular key. use like this. `ModelState.AddModelError("yourModelPropety", "error");` here you are setting model error for particular key.
Use ModelState.IsValid property. it tells you if is there any model errors have been added to ModelState. ModelState.Isvalid
try like this.
ModelState.AddModelError("Email ", "error"); here you are setting model error for particular key.
if(!ModelState.IsValid)
{
// do something to display errors .
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
DoSomethingWith(error);
}
}
}
Problem
Now,I have a model like this: ``` namespace TestMVC.Models.ViewModel { public partial class User { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } } [MetadataType(typeof(UserMetaData))] public partial class User { } public class UserMetaData { [Display(Name = "Name")] public string Name { get; set; } [Display(Name = "Age")] public int Age { get; set; } [Display(Name = "Email")] [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "The email is invalid")] public string Email { get; set; } } } ``` and i have a method like this : ``` public ActionResult ValidCheck() { ModelState.AddModelError("error", "error"); Models.ViewModel.User model = new Models.ViewModel.User(); model.Age = 12; model.Name = "Andy He"; model.Email = "123"; //TryValidateModel(model); } ``` I want to through the method to Check if model is valid and get the error message ,I try to use TryValideModel but it only can get the result which the model is valid ,can't get the error message ,Is there a method can do this?could you help me?