2015-11-04 47 views
1

我正在編寫一個自定義MVC驗證屬性,該屬性依賴於模型中的另一個命名屬性。實施IClientValidatable我的代碼看起來是這樣的:獲取MVC客戶端驗證對象列表的完整屬性名稱

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

你能告訴模型(S)和財產您@StephenMuecke將其應用到 –

+0

編輯的顯示爲例 –

+0

你不(和S不應該)在屬性中需要_「全名」_。假設你使用'protected override ValidationResult IsValid(object value,ValidationContext validationContext)',那麼'validationContext'就是'Item'模型。我假設你想要的是在你的客戶端腳本中獲得相應的'DependentProperty'? –

回答

0

你不驗證屬性需要完全合格的屬性名,你不能確定它在任何情況下,因爲驗證上下文(你的情況)的typeof 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; 
}); 
+0

客戶端,這幾乎是我連接到的萬無一失的庫。我想我正在尋找的答案是,你不能,因爲該屬性沒有上下文。 –