获取对象列表的MVC客户端验证的完整属性名称

本文关键字:属性 客户端 取对象 列表 MVC 获取 验证 | 更新日期: 2023-09-27 18:20:28

我正在编写一个自定义MVC验证属性,该属性依赖于模型中的另一个命名属性。实现IClientValidatable我的代码如下:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules
    (ModelMetadata metadata, ControllerContext context)
    {            
        var name = metadata.DisplayName ?? metadata.PropertyName;
        ModelClientValidationRule rule = new ModelClientValidationRule()
        { ErrorMessage = FormatErrorMessage(name), ValidationType = "mycustomvalidation" };
        rule.ValidationParameters.Add("dependentproperty", dependentProperty);
        yield return rule;
    }

问题是我试图在元素列表中使用它。依赖属性在名称为MyListOfObjects[0].DependentProperty的视图中呈现,验证规则呈现为data-val-mycustomvalidation-dependentproperty="DependentProperty"

如何从GetClientValidationRules(ModelMetadata metadata, ControllerContext context)中访问依赖属性的全名,使其呈现为data-val-mycustomvalidation-dependentproperty="MyListOfObjects[0].DependentProperty"

模型如下:

public class MyClass
{
    public string SomeValue { get; set; }
    public List<Item> MyListOfObjects  { get; set; }
    public class Item
    {
        [MyCustomValidation("DependentProperty")]
        public int MyValidatedElement  { get; set; }
        public int DependentProperty  { get; set; }
    }
}  

获取对象列表的MVC客户端验证的完整属性名称

验证属性中不需要完全限定的属性名,而且在任何情况下都无法确定它,因为验证上下文(在您的情况下)类型为Item(该属性没有父MyClass的上下文)。

需要全名的地方在客户端脚本中(当您将adapter添加到$.validator.unobtrusive时)。以下脚本将返回依赖属性的id属性

myValidationNamespace = {
  getDependantProperyID: function (validationElement, dependantProperty) {
    if (document.getElementById(dependantProperty)) {
      return dependantProperty;
    }
    var name = validationElement.name;
    var index = name.lastIndexOf(".") + 1;
    dependantProperty = (name.substr(0, index) + dependantProperty).replace(/['.'[']]/g, "_");
    if (document.getElementById(dependantProperty)) {
        return dependantProperty;
    }
    return null;
  }
}

然后,您可以在初始化客户端验证时使用它

$.validator.unobtrusive.adapters.add("mycustomvalidation", ["dependentproperty"], function (options) {
  var element = options.element;
  var dependentproperty = options.params.dependentproperty;
  dependentproperty = myValidationNamespace.getDependantProperyID(element, dependentproperty);
  options.rules['mycustomvalidation'] = {
    dependentproperty: dependentproperty
  };
  options.messages['mycustomvalidation'] = options.message;
});