2

項目在ModelStateDictionary關鍵。如果這是我的視圖模型:什麼決定的集合屬性

public class ViewModel{ 
     public string SimpleProperty{get;set;} 
     public SubViewModel ComplexProperty{ get;set;} 
     public SubViewModel[] ComplexPropertyArray{ get; set; } 
} 

public class SubViewModel{ 
     public string NestedSimpleProperty{get;set;} 
} 

那麼這將是分配給ModelStateDictionary爲默認的錯誤消息鍵:

  1. ViewModel.SimpleProperty(見下面更新)
  2. ViewModel.ComplexProperty(見下文更新)
  3. ViewModel.ComplexProperty.NestedSimpleProperty(見下文更新)
  4. ViewModel.ComplexPropertyArray(見下文更新)
  5. ViewModel.ComplexPropertyArray [0]
  6. ViewModel.ComplexPropertyArray [0] .NestedSimpleProperty

更新我發現這在反射器:

protected internal static string CreateSubPropertyName(string prefix, string propertyName) 
{ 
    if (string.IsNullOrEmpty(prefix)) 
    { 
     return propertyName; 
    } 
    if (string.IsNullOrEmpty(propertyName)) 
    { 
     return prefix; 
    } 
    return (prefix + "." + propertyName); 
} 

所以,我認爲,涵蓋了除#5,#6

回答

2

如果您要求NestedSimpleProperty必需:

public class SubViewModel 
{ 
    [Required] 
    public string NestedSimpleProperty{ get; set; } 
} 

,然後你必須在其中具有用於對應於每個項目的ComplexPropertyArray集合中的這個屬性的多個文本框形式然後將被用於錯誤消息的關鍵將是ComplexPropertyArray[i].NestedSimpleProperty其中i表示元素在索引包含一個空值的數組。

+0

我會有任何與'ViewModel.ComplexPropertyArray [0]'相關的錯誤,或者只有它的屬性? – smartcaveman 2011-03-21 14:29:30

+0

@smartcaveman,不,在這種情況下,您將只有與'ComplexPropertyArray [0] .NestedSimpleProperty'關聯的錯誤。你可以在你的控制器的POST動作中檢查ModelState屬性,在其中你可以找到ModelState [「ComplexPropertyArray [0] .NestedSimpleProperty」] .Errors;'value。 – 2011-03-21 14:30:31

+0

@Darin,好的,最後一個問題 - 我可以有一個與模型根相關的錯誤(如在裝飾'ViewModel'的驗證屬性中)?如果是這樣,它的關鍵是什麼? – smartcaveman 2011-03-21 14:33:30