2010-07-19 108 views
2

說我有一個模型,如下所示:模型驗證與字典

public class MyViewModel { 
    //some properties 
    public string MyString {get;set;} 
    public Dictionary<string,string> CustomProperties {get;set;} 
} 

而且我提出的字典屬性,像這樣:

<%= Html.EditorFor(m => m.CustomProperties["someproperty"]) %> 

一切工作正常,但我實現了自定義驗證器來驗證這個詞典的屬性,但是當返回ModelValidationResult時,我無法獲得正確引用的成員名稱(我相信這應該是CustomProperties[someproperty])。屬性列表中的所有項都被正確綁定到它們的錯誤(我想在文本框中輸入錯誤類,以便突出顯示它)。

這裏是我的自定義驗證碼到目前爲止

public class CustomValidator : ModelValidator 
{ 
    public Custom(ModelMetadata metadata, ControllerContext controllerContext) : base(metadata, controllerContext) 
    { 
    } 

    public override IEnumerable<ModelValidationResult> Validate(object container) 
    { 
     if (Metadata.PropertyName.Equals("mystring", StringComparison.OrdinalIgnoreCase)) 
     { 
      yield return new ModelValidationResult() {Message = "normal property validator works!!"}; 
     } 
     else if (Metadata.PropertyName.Equals("customproperties", StringComparison.OrdinalIgnoreCase)) 
     { 

      yield return new ModelValidationResult() { MemberName = "CustomProperties[someproperty]", Message = "nope!" }; 
     } 
    } 
} 

看起來象是在MemberName屬性填充進一步上漲,而忽略了我擺在那裏

乾杯, 阿馬爾

+0

更新:我研究過這個問題,看起來modelState錯誤數據是由DefaultModelBinder創建的,它間接使用一個名爲ModelValidator.CompositeModelValidator的私有類。此私有類只調用CreateSubPropertyName,並沒有考慮潛在的索引器。明天某個時候我會發布解決方案。 – amarsuperstar 2010-07-19 21:08:08

回答

1

在我看來,你正在驗證比需要更困難。您是否看過內置於框架中的DataAnnotations? Scott Gu's blog talks about this。這是一個非常好的(而且很簡單)的方法來驗證模型。

+0

是的,我現在正在使用它,但是我需要稍微擴展一下,因爲我在字典中的屬性是動態的(就像下面的模式一樣,但是這超出了我的控制範圍,第三方產品)。我已經有結構,它會告訴我哪個鍵有哪些驗證要求,所以現在我只需要將它應用到我的詞典:) – amarsuperstar 2010-07-19 19:47:18

+0

我得到它與字典在最後工作,但問題進一步下行讓我決定使用生成的POCO視圖模型,所以我不必針對框架進行工作。 – amarsuperstar 2010-07-23 10:28:15

+0

在我看來,這個迴應並沒有回答這個問題。努力瞭解如何被接受爲如此...... – marsop 2016-10-24 10:20:04