Question

I have an Entity Framework 4.1 model that supports multiple ASP.NET MVC web applications. I use DataAnnotations to define and localize label text and validation rules and error messages.

For some applications, I need the label text for certain fields to differ from the standard, model-defined text. This is easy to achieve for the labels themselves: I retrieve the text I need from a local resource file, associated with the view. However, the label text is also used in validation error messages such as "{fieldname} must have a maximum length of 50 characters".

What is the best way to alter the validation messages without changing the Annotations on the model classes?

Était-ce utile?

La solution 2

You have coupled your validation to your entity models. The way to avoid this is to create view models from your entities and put the validation on to those.

Example: If you have the Entity...

public class Product
{
    public string Name {get; set;}
}

you could create two different view models:

public class ProductPageViewModel1
{
    [Required]
    public string Name {get; set;}
}

public class ProductPageViewModel2
{
    [DisplayName("Foo")]
    public string Name {get; set;}

}

Map the entity to the view model and use these in your views.

Autres conseils

Try to redefine error messages in controller for specific cases, like this:

Model:

public class Company
    {
        [Required(ErrorMessage = "The field is required")]
        public string CompanyName { get; set; }
        public string Address { get; set; }
    }

controller:

 [HttpPost]
        public ActionResult Index(Company company)
        {
            if(ModelState.IsValid)
            {
                //your code
            }

            // your custom validation message here
            if (ModelState["CompanyName"].Errors.Any())
                ModelState["CompanyName"].Errors[0] = new ModelError("custom error message");

            return View();
        }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top