0

我在包含外来对象模型的模型中遇到数据注释验证问题。

让我们说

Class Foo
{
    public virtual Int Id {get; set;}

    [Required]       
    public virtual String Name {get; set;}
 }

 Class Bar
 {
    public virtual Int Id {get; set;}

    [Required]
    public virtual String AnotherName {get; set;}

    public virtual Foo foo  {get; set;}
 }

创建 BAR 时,FOO 不是强制性/必需的。

但是当我尝试检查 BAR 的 HTTPPOST 中的 ModelState 时,它​​说模型状态无效,并报告 FOO 列丢失。

[HTTPPOST]
public ActionResult SaveBar(BAR bar)
{
if (ModelState.IsValid)
    SaveBar(bar);

} 

我已将 FOO 设置为 null,尝试过 TryUpdateModel,但仍然没有帮助。

编辑 我正在处理实体而不是查看模型

还有..如何告诉模型绑定器在绑定 BAR 时不要检查 FOO ......

编辑 修改示例..

4

4 回答 4

2

当您点击“SaveBar()”时,模型绑定器似乎将 Foo 实例化为 Bar 对象的成员。因此,正如您所期望的那样,Foo 上的属性验证会触发。

这就是我要做的:删除属性验证并走一条不同的路线,可能就像您从控制器操作调用的自定义验证方法一样,用于正常的“Foo”操作。“SaveBar()”可以检查 Foo 的默认状态并决定是否调用该验证,具体取决于。

于 2013-04-19T19:47:20.193 回答
0

Don't use [Required] on your model's id. I'm not sure whether you're dealing with entities or view models here, but in general, the id should be allowed to be unset. In the case of entities, the id will not be set until it is saved to the database (typically) and in the case of a view model, you might be representing an entity that has not previously been saved (and thus has no id).

[Required] has only two real uses, so you should understand exactly what those are and then only apply the attribute accordingly:

1) On an entity, [Required] will imply NOT NULL. It really only makes sense on strings since every other scalar type is NOT NULL by default.

2) On a view model being used to accept form data from a POST. This will require that the field not be blank. If your id is not a form field being presented to the user for input (which I highly doubt it is), then it should not be required.

于 2013-04-19T18:46:40.577 回答
0

@hgrathi,你不明白的是,一旦你在 Foo 中指定了 Name , Foo 现在在 Bar 下是必需的。

解决此问题的一种方法是通过实现 IModelBinder 创建自定义模型绑定器。

于 2013-04-19T20:28:59.643 回答
0

它不像你想象的那样工作。ModelState无效,因为您根据要求声明了 的字段Foo。如果您的视图不接受并传递值Foo.IdFoo.Name那么您将得到一个无效的ModelState.

于 2013-04-19T18:33:36.930 回答