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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Carriage Return (ASCII chr 13) is missing from tex
- MVC-Routing,Why i can not ignore defaults,The matc
- Why am I getting UnauthorizedAccessException on th
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.If you simply want to bind or validate a model, but skip the Required property in your controller, you can do something like:
Yes, it is possible using the MetadataType class, e.g:
And test it:
I tried Mahmoud's answer, but it didn't work for me without a few changes. Adding this as an answer so I can give the code that did in case it helps someone else, but full credit to Mahmoud Hboubati - I've upvoted your answer.
In my situation I had a base DTO class with a DbGeography property that was required for an MVC project which used a custom EditorTemplate and DisplayTemplate for the DbGeography type. But for posting a model to a Web API controller I wanted to have latitude/longitude fields added to a subclass of that DTO instead, which would be used to create and set an instance of a DbGeography class to set the value on the DbGeography property. Problem was, I couldn't make the DbGeography property not required on the subclass only.
When the boolean value was passed in the constructor using Mahmoud's approach, it never seemed to override the default value for me. That might be because I'm using Web API and registering the attribute using the factory approach, like below (in Global.asax.cs Application_Start method):
I had to change the attribute class to this:
Base Class:
Subclass:
Note, I used same method as Mahmoud did above for registering the attribute in my MVC project:
@HackedByChinese method is fine, but it contains a problem
This code give you a validation error in
ModelState
EVEN if you useDerivativeModel
on the form,override
doesn't work either, so you cannot deleteRequired
attribute by overriding or renewin it, so I came to a some sort of a workaroundI have a base model with no validation attributes and derived classes
You can use a custom validation attribute (it might be derived from RequiredAttribute):
and then regester it in
Application_Start
using this code line: