【问题标题】:Model Validation with dictionary使用字典进行模型验证
【发布时间】:2010-07-19 17:22:47
【问题描述】:

假设我有一个这样的模型:

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 属性,而忽略了我在其中输入的内容

干杯, 阿马尔

【问题讨论】:

  • 更新:我对此进行了调查,似乎模型状态错误数据是由 DefaultModelBinder 创建的,它间接使用了一个名为 ModelValidator.CompositeModelValidator 的私有类。这个私有类只调用 CreateSubPropertyName 并且不考虑潜在的索引器。我明天某个时候会发布一个解决方案。

标签: asp.net-mvc validation asp.net-mvc-2 modelbinders


【解决方案1】:

在我看来,您使验证变得比实际需要的更加困难。您是否看过框架中内置的 DataAnnotations? Scott Gu's blog talks about this。这是验证模型的一种非常好(且简单)的方法。

【讨论】:

  • 是的,我现在正在使用它,但是我需要稍微扩展它,因为我在字典中的属性是动态的(就像下面的架构一样,但这是我无法控制的,因为我在 3rd 方产品上构建一些东西)。我已经有结构可以告诉我哪个键有哪些验证要求,所以现在我只需要将它应用到我的字典:)
  • 我最终将它与字典一起使用,但是进一步的问题使我决定使用生成的 POCO 视图模型,因此我不必针对框架工作。
  • 在我看来,这个回复没有回答这个问题。努力理解如何被接受......
  • 答案不应该被接受 我完全同意@marsop
猜你喜欢
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多