I have an MVC 3 application. I have a model called UserModel that contains an email field, validated for unique with RemoteAttribute. I want to use UserModel on 2 Views - EditU
You can use the partial validation technique to modify the validation results. This example will discard any errors for the Email field.
public class DontValidateEmailAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var modelState = filterContext.Controller.ViewData.ModelState;
var incomingValues = filterContext.Controller.ValueProvider;
var key = modelState.Keys.Single(x => incomingValues.Equals("Email"));
modelState[key].Errors.Clear();
}
}
and apply this attribute to your Edit Controller.
I learnt this technique from Steve Sanderson's Pro ASP NET MVC 3. He uses the technique to validate a model that has required fields but the data entry is a multistep wizard. If the value has not been returned in the form post, he removes the errors for that property.
A good way to solve this is to pass the usermodel id as an adittional field into the remote validation method. This will be blank or null on create but populated on edit. You can then add logic to the remote validation method to check the id.
See example below
[Remote("ValidationMethod", "UserModel", AdditionalFields = "Id", ErrorMessage = "Error message")]