1

I am using ASP.NET MVC 5 and trying to do custom validation using data annotations of a view model object that is instantiated within the controller post method and reloaded from EF. Only a few of the model properties are populated when posting from the client and the rest are reloaded using EF. The model is complex and all parts of it implement IValidatableObject. The code within the Validate method fires for the new view model after everything is loaded correctly, but it does not do anything with the data annotations applied to the model.

So for instance, if my model has the EmailAddress attribute applied to a field, it works great on the client side, but it is ignored on the server side when validating against the new view model. How do I get my Validate method to take the data annotations into account?

Here's the code for the controller action...

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult SignUp(SignUpEM em) {
    if (em == null) {
        return RedirectToAction(MVC.Sheet.Index());
    }
    SignUpSheet signUpSheet = db.GetSignUpSheet(em.SheetId);
    SignUpEM newEM = Map.ToSignUpEM(signUpSheet);
    foreach (var sourceField in em.Fields) {
        FieldEM targetField = newEM.Fields.FirstOrDefault(f => f.FieldDefId == sourceField.FieldDefId && f.Id == sourceField.Id);
        if (targetField.FieldType.IsEditable()) {
            if (targetField.FieldType.IsBoolean()) {
                ((BooleanFieldEM)targetField).BooleanValue = ((BooleanFieldEM)sourceField).BooleanValue;
            }
            else {
                targetField.Value = sourceField.Value;
            }
            targetField.SetFullyLoaded();
        }
    }
    // This line is here to simulate an invalid value passed into an email field.
    newEM.Fields[0].Value = "invalid";
    newEM.SetFullyLoaded();
    ModelState.Clear();
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(newEM, new ValidationContext(newEM, null, null), validationResults, true);
    foreach (var result in validationResults) {
        if (result == null) { continue;  } // otherwise we need to avoid duplicates.
        if (result.MemberNames.Count() == 0)
            ModelState.AddModelError(String.Empty, result.ErrorMessage);
        else
            foreach (var name in result.MemberNames)
                ModelState.AddModelError(name, result.ErrorMessage);
    }

    if (!ModelState.IsValid) {
        return View(newEM);
    }

    SignUp su = Map.ToSignUp(em);
    db.AddSignUp(su);
    return RedirectToAction(MVC.SignUp.SignUp(em.SheetId));
}

Here's the validation code for SignUpEM...

private bool fullyLoaded;
internal void SetFullyLoaded() {
    fullyLoaded = true;
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
    if (fullyLoaded) {
        foreach (var f in Fields)
            foreach (var vr in f.Validate(validationContext))
                yield return vr;

        if (ListIntro == null)
            yield return new ValidationResult("ListIntro is required for now.");
    }
}

And the validation code for FieldEM...

private bool fullyLoaded;
internal void SetFullyLoaded() {
    fullyLoaded = true;
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
    if (fullyLoaded) {
       if (Optional == false && String.IsNullOrEmpty(Value)) {
            string message = string.Format("{0} is required.", DisplayName);
            yield return new ValidationResult(message);
        }
    }
}
5
  • Post the relevant controller action, otherwise we're just guessing.
    – John H
    Commented Dec 3, 2013 at 17:59
  • I posted the controller along with Validate methods on the models. Commented Dec 3, 2013 at 18:52
  • Well, your question is about the DataAnnotation attributes, and the fact that they don't work on the server side. You need to post your View and your Model, where the DataAnnotation attributes have been applied.
    – ataravati
    Commented Dec 3, 2013 at 19:09
  • "If you want to use the validators with the classes generated by the Entity Framework then you need to create meta data classes. You apply the validators to the meta data class instead of applying the validators to the actual class." So I think that instantiating the view model instance with the model is probably the same thing. You may need to use AutoMapper if your going to instantiate the vm with model or use DI to instantiate the vm instance.
    – stink
    Commented Dec 4, 2013 at 2:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.