Reputation: 930
In my MVC application I have a requirement where I want user to insert Unique value in a column.
i.e.: Username
should be unique in Users
table.
I used [Indes(IsUnique = true)]
data annotation in my model.
But when I insert duplicate value in the field it throws an exception, but I want to display an Error Message on my View saying Please try with a different Username
Please help me what should I do here?
Upvotes: 0
Views: 1493
Reputation: 378
You can use one of those:
Write your CustomValidator (ny recommendation)
[CustomRemoteValidator(ErrorMessage = @"Username already in use")]
public string Username{ get; set; }`
And override IsValid method
public override bool IsValid(object value)
{
return !(this.DbContext.Set<User>().Any(a =>
a.Username.Equals((string)value));
}
Check it in your business layer.
SaveChanges()
method.Upvotes: 2