小编典典

MVC4和IClientValidatable-服务器端验证的自动AJAX调用

ajax

我正在寻求在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- 为“打开”或“关闭”的验证器规则创建适配器。该规则不需要其他参数

所以在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)我希望它可以在各种自定义验证属性中重复使用。我该如何使它通用?

抱歉,如果我是从痣山上爬下来的。谢谢你的时间 :)

拉斯


阅读 199

收藏
2020-07-26

共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非侵入式验证),您可能仍需要其他服务器端验证。

有关详细示例,请参阅如何:在ASP.NET MVC中实现远程验证。

2020-07-26