Is there a way to override ModelState.IsValid
?
Some of the entities to be validated are just attached entities, so all the fields except the ID are not to be validate as the entity is in state Unchanged
.
Is there a way to do this?
Has anyone faced this issue before?
Update
Say I have the following action:
[HttpPost]
public ActionResult SaveEntity(MyEntity entity)
{
var isValid = ModelState.IsValid; //false
}
Since the model validates all properties and all descendant properties of entity
, there has to be a way to check on each entity of those descendants, whether it's attached to the context, and if it is, remove error from ModelState
, something like the following:
public ActionResult TryValidateDetachedModel(MyEntity entity, DbContext context)
{
foreach (var ms in ModelState.Where(ms => ms.Value.Errors.Any()).ToArray())
// should iterate over something like GetAllEntityTypesMetadata()
{
var entity = GetEntityFromMetadata(ms);
if (context.Entry(entity).State == EntityState.Unchanged)
{
ms.Value.Errors.Clear();
}
}
}
What I'm trying to do in the above pseudo code is to check the entities in the validation chain, and if one of them is attached as Unchanged
, skip validation / remove its errors.
Right now I have to do it hard-coded manually by checking ModelState.Key
, I'm looking for a more generic and efficient way.
To clear all errors use next
ModelState.Clear();
regards