Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override the required attribute on a property in a model?

Tags:

I'm curious to find out if it is possible to override the [Required] attribute that has been set on a model. I'm sure there most be a simple solution to this problem, any takers?

like image 751
Ryan Smith Avatar asked Jan 18 '12 00:01

Ryan Smith


2 Answers

Depends on what precisely you are doing. If you are working with a subclass, using the model with the Required attribute as the base, you can do this:

Redefine the property with the new keyword, rather than override it.

public class BaseModel {     [Required]     public string RequiredProperty { get; set; } }   public class DerivativeModel : BaseModel {     new public string RequiredProperty { get; set; }  } 

If you simply want to bind or validate a model, but skip the Required property in your controller, you can do something like:

public ActionResult SomeAction() {      var model = new BaseModel();       if (TryUpdateModel(model, null, null, new[] { "RequiredProperty" })) // fourth parameter is an array of properties (by name) that are excluded      {           // updated and validated correctly!           return View(model);      }      // failed validation      return View(model); } 
like image 171
moribvndvs Avatar answered Sep 20 '22 00:09

moribvndvs


@HackedByChinese method is fine, but it contains a problem

public class BaseModel {     [Required]     public string RequiredProperty { get; set; } }  public class DerivativeModel : BaseModel {     new public string RequiredProperty { get; set; } } 

This code give you a validation error in ModelState EVEN if you use DerivativeModel on the form, override doesn't work either, so you cannot delete Required attribute by overriding or renewin it, so I came to a some sort of a workaround

public class BaseModel {     public virtual string RequiredProperty { get; set; } }  public class DerivativeModel : BaseModel {     [Required]     public override string RequiredProperty { get; set; } }  public class DerivativeModel2 : BaseModel {     [Range(1, 10)]     public override string RequiredProperty { get; set; } } 

I have a base model with no validation attributes and derived classes

like image 43
Saito Avatar answered Sep 22 '22 00:09

Saito