it is necessary for me to validate whether a value is already in the database or not. Therefore I wrote an own ValidationAttribute that checks it. The problem is I add this to the attribute in the model:
[UniqueAttribute(ErrorMessage = "This title already exists")]
That works fine in the add view but when editing this object I don't know how to handle this, because, if the user doesn't change the title, there will also be an error message because the validation is executed. I could use a modelview without this ValidationAttribute but if the user changes the title to another title that still exists, it would breach the uniqueness.
Do you have any idea how I can validate for the edit view if the title would be unique after updating the object or not?
Thank you.
example:
public class UniqueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
MyDataContext db = new MyDataContext();
foreach (var item in db.AnyObjects.ToList())
if (item.Title.Equals(value))
return false;
return true;
}
}
This works good when adding an object but not when editing.