我正在尝试实现远程客户端验证以检查是否已经使用了用户名。我已阅读phil haack's帖子和msdn article,并提出以下实施内容:
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 };
}
}
我的视图模型类具有以下远程属性:
[Remote(Controller = "SignUp",Action = "IsUsernameAvailable")]
public string Username { get; set; }
我正在使用jquery的验证如下:
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;
});
}
});
在我的控制器中,我有一些操作方法如下:
public JsonResult IsUsernameAvailable(string userName)
{
var isUsernameAvailable = _userService.IsUsernameAvailable(userName);
if (isUsernameAvailable)
{
return Json(true);
}
return Json(false);
}
由于某些原因,即使我的actiom方法IsUsernameAvailable很难恢复,也会始终显示验证消息。我在这里做错了什么?
答案 0 :(得分:0)
您的调用RemoteAttribute.IsValid()始终返回true。添加您的IsUsernameAvailable检查并根据需要返回true或false。
IsValid()函数告诉模型是否触发错误。
答案 1 :(得分:0)
尝试使用
发送字符串“true”和“false”而不是json值return Content("true")
和
return Content("false");
答案 2 :(得分:0)
尝试Json(true,JsonRequestBehavior.AllowGet);或者Json(false,JsonRequestBehavior.AllowGet);