【问题标题】:What determines the key in the ModelStateDictionary for Items of Collection Properties什么决定了集合属性项的 ModelStateDictionary 中的键
【发布时间】:2011-07-19 17:06:52
【问题描述】:

如果这是我的视图模型:

 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

之外的所有内容

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 modelstate addmodelerror modelstatedictionary


    【解决方案1】:

    如果您将NestedSimpleProperty 设为必需:

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

    然后您有一个表单,其中您有多个文本框用于此属性,对应于 ComplexPropertyArray 集合中的每个项目,然后将用于错误消息的键将是 ComplexPropertyArray[i].NestedSimpleProperty 其中i 表示索引数组中包含空值的元素。

    【讨论】:

    • 我会有任何与ViewModel.ComplexPropertyArray[0] 相关的错误,还是仅与它的属性相关的错误?
    • @smartcaveman,不,在这种情况下,您只会遇到与ComplexPropertyArray[0].NestedSimpleProperty 关联的错误。您可以在控制器的 POST 操作中检查 ModelState 属性,您将在其中找到 ModelState["ComplexPropertyArray[0].NestedSimpleProperty"].Errors; 值。
    • @Darin,好的,最后一个问题 - 我是否有与模型根相关的错误(如装饰 ViewModel 的验证属性)?如果是这样,它的密钥是什么?
    • @smartcaveman,通常当您编写自定义验证器属性并用它装饰您的视图模型类时,ModelState 中没有相应的键 => 它将是一个空字符串。在使用数据注释时,这是一个很棒的 PITA,因为您只能使用验证摘要在视图中显示错误消息。
    • @smartcaveman,我个人使用FluentValidation.NET而不是数据注释来执行我的验证逻辑,我没有这样的问题。我更喜欢命令式验证而不是声明式验证,因为它更强大,并且允许我处理复杂的验证场景。
    猜你喜欢
    • 2012-05-09
    • 2016-02-16
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多