开发者

Remote Validation With ASP.NET MVC2 and jQuery

I am trying to implement remote client validation to check if a username has already been taken. I have read phil haack's post and a msdn article and come up with the following implementation:

   public class RemoteAttribute : ValidationAttribute
    {
        public string Action { get; set; }
        public string Controller { get; set; }

        public override bool IsValid(object value)
        {
            return true;
        }
    }


public class RemoteValidator : DataAnnotationsModelValidator<RemoteAttribute>
{

    public RemoteValidator(ModelMetadata metadata, ControllerContext context, RemoteAttribute validationAttribute) :
        开发者_高级运维base(metadata, context, validationAttribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
                                             {
            ErrorMessage = Messages.DuplicateUsername,
            ValidationType = "remote"
        };

        rule.ValidationParameters.Add("url", Attribute.Controller + "/" + Attribute.Action);
        return new[] { rule };
    }
}

My view model class has a remote attribute as follows:

   [Remote(Controller = "SignUp",Action = "IsUsernameAvailable")]
   public string Username { get; set; }

I am using jquery's validation as follows:

jQuery.validator.addMethod("remote", function (value, element, params) {
    if (this.optional(element)) {
        return true;
    }

    if (value != '') {
        $.post(params.url, { username: value }, function (response) {
            return response;
        });
    }

});

In my controller I have a some action methods as follows:

  public JsonResult IsUsernameAvailable(string userName)
    {
        var isUsernameAvailable = _userService.IsUsernameAvailable(userName);
        if (isUsernameAvailable)
        {
            return Json(true);
        }

        return Json(false);
    }

For some reason even tough my actiom method IsUsernameAvailable returns true the validation message is always displayed. What am I doing wrong here?


Your call RemoteAttribute.IsValid() is always returning true. Add your IsUsernameAvailable check and return true or false as appropriate.

The IsValid() function is what tells the model whether to trigger an error or not.


try Json(true, JsonRequestBehavior.AllowGet); or Json(false, JsonRequestBehavior.AllowGet);


Try sending string "true" and "false" instead of json values with

return Content("true") 

and

return Content("false");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜