我正在编写一个自定义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; }
}
}
答案 0 :(得分:1)
您在验证属性中不需要完全限定的属性名称,并且在任何情况下都无法确定它,因为验证上下文是(在您的情况下)typeof Item
(该属性没有上下文的属性)父MyClass
)。
您确实需要全名在客户端脚本中(将adapter
添加到$.validator.unobtrusive
时。以下脚本将返回依赖属性的id
属性< / p>
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;
});