What determines the key in the ModelStateDictionary for Items of Collection Properties

564 views Asked by At

If this is my view model:

 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;}
 }

Then what would be the default error message keys assigned to a ModelStateDictionary for:

  1. ViewModel.SimpleProperty (see update below)
  2. ViewModel.ComplexProperty (see update below)
  3. ViewModel.ComplexProperty.NestedSimpleProperty (see update below)
  4. ViewModel.ComplexPropertyArray (see update below)
  5. ViewModel.ComplexPropertyArray[0]
  6. ViewModel.ComplexPropertyArray[0].NestedSimpleProperty

Update I found this in reflector:

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

So, I think that covers everything except for #5 and #6

1

There are 1 answers

14
Darin Dimitrov On BEST ANSWER

If you make the NestedSimpleProperty required:

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

and then you have a form in which you have multiple textboxes for this property corresponding to each item in the ComplexPropertyArray collection then the key that will be used for error messages will be ComplexPropertyArray[i].NestedSimpleProperty where i represents the index of the element in the array which contains an empty value.