mardi 26 juillet 2016

Call a specified action from a validation attribute

I am currently creating an attribute similer to the existing "Remote" attribute. The client side validation is stright forward with javascipt calling an action to check (againt our database) that the input is valid. The problem is when it comes to server side validation I cannot work out how I can call the action. The "Remote" attribute is no help since "Does no server-side validation"

No client side code is show since thats working fine.

The attribute

[AttributeUsage(AttributeTargets.Property)]
public class AjaxValidation : Attribute, IModelValidator {

    private readonly string _action;
    private readonly string _area;
    private readonly string _controller;

    public AjaxValidation(string action, string controller = null, string area = null) {
        _action = action;
        _area = area;
        _controller = controller;
    }

    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context) {

        List<ModelValidationResult> result = new List<ModelValidationResult>();

        //Need to call the action and check the result here

        //Create the controller with reflection?

        //Call the method with reflection?

        if(false was returned) {
            result.Add(new ModelValidationResult("", "{0} is invalid"));
        }

        return result;

    }
}

A model showing it's usage

[AjaxValidation ("Validate", "Home", "Examples")]
public string Value{ get; set; }

and an action that model would call (Also used by the client side)

public ActionResult Validate(string id) {

    if (id.Length == 3) {
        return Json(new { Success = true });
    } else {
        return Json(new { Success = false });
    }

}





Aucun commentaire:

Enregistrer un commentaire