【问题标题】:MVC4 & IClientValidatable - Automatic AJAX calls to server side validationMVC4 和 IClientValidatable - 对服务器端验证的自动 AJAX 调用
【发布时间】:2015-01-17 07:09:06
【问题描述】:

我希望在 MVC4 中实现自定义客户端验证。我目前可以很好地使用标准属性,例如我的模型中的这个

public class UploadedFiles
{
    [StringLength(255, ErrorMessage = "Path is too long.")]
    [Required(ErrorMessage = "Path cannot be empty.")]
    [ValidPath]
    public string SourceDirectory { get; set; }
}

所以 StringLength 和 Required 都会自动转换为一些 JQuery 客户端验证。目前“有效路径”仅适用于服务器端。验证总是需要在服务器端进行,因为只有服务器才能验证路径是否有效,您不能在客户端进行此操作。

服务器端代码如下

public class ValidPathAttribute : ValidationAttribute, IClientValidatable
{
    public string SourceDirectory;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string path = value.ToString();
        string message = string.Empty;

        var fileSystemSupport = new FileSystemSupport(Settings, new WrappedFileSystem(new FileSystem()));

        if (fileSystemSupport.ValidateNetworkPath(path, out message))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(message);
    }
} 

这很好用。现在我希望通过 ajax 调用来实现这一点,进入“IClientValidatable”和“GetClientValidationRules”。按照我写的书

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "validpath";
        yield return rule;
    }

我相信我现在必须编写一些自定义验证脚本代码、适配器(用于识别所需的元数据)和验证规则本身(验证器,由 rule.ValidationType 引用)。

我觉得不用写适配器,直接用就行了

addBool - 为“on”或“off”的验证器规则创建一个适配器。该规则不需要额外的参数

所以在 UploadedFiles.js 我现在有了

$.validator.unobtrusive.adapters.addBool("validpath", "required");

在我看来

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/UploadedFiles.js")
}

相信这足以连接一切,但我现在需要编写 javascript 验证器。这些存在于 jQuery.validator 对象中,可以使用 $.validator.addMethod 添加。

由于以下几个原因,这让我有点不适应:

1) 这是正确的处理方式吗,如果我的验证存在于服务器端,那么这是一个 ajax 调用吗?这将需要是同步的。

2) 是否有一个 jQuery 元素我应该重复使用来执行此操作?我希望我已经完成了服务器端的工作,我可以启用一些魔法来将客户端连接到它(很像标准验证)。

3) 我希望它可以在各种自定义验证属性中重复使用。我怎样才能使这个通用?

抱歉,如果我把鼹鼠山变成了一座山。谢谢你的时间:)

罗斯

【问题讨论】:

标签: jquery ajax asp.net-mvc-4 validation


【解决方案1】:

MVC 带有 RemoteAttribute,它在内部对控制器方法进行 ajax 调用,该方法返回一个 Json 值,指示验证是成功还是失败

public JsonResult IsValid(string SourceDirectory)
{
  if (someCondition) //test if the value of SourceDirectory is valid
  {
    return Json(true, JsonRequestBehavior.AllowGet); // indicates its valid
  }
  else
  {
    return Json(false, JsonRequestBehavior.AllowGet); // indicates its not valid
    // or return Json("A custom error message that overrides the default message defined in the attribute");
  }
}

并用

装饰您的财产
[Remote("IsValid", "YourController", ErrorMessage = "The path is not valid")]
public string SourceDirectory { get; set; }

注意:RemoteAttribute 仅用于客户端(jquery 不显眼的验证),您可能仍需要额外的服务器端验证。

详细示例请参考How to: Implement Remote Validation in ASP.NET MVC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多