【发布时间】:2013-06-17 17:22:04
【问题描述】:
在属性上添加简单的数据注释很棒,
public class UnicornViewModel
{
[Required]
public string Name { get; set; }
但是假设我有这样的事情:
public class SuperPower
{
public class Name { get; set; }
}
public class UnicornViewModel
{
[Required]
public string Name { get; set; }
public SuperPower PrimarySuperPower { get; set; }
public SuperPower SecondarySuperPower { get; set; }
如何在 PrimarySuperPower.Name 上应用Required 属性,同时为 SecondarySuperPower.Name 保留可选属性?最好是 1. 与客户端验证相关的东西和 2. 没有任何特殊处理,例如检查 Action/Custom 验证器中 PrimarySuperPower.Name 的值,如果它为空,则添加 ModelState 错误。如果有类似的东西那就太好了:
[Required(p => p.Name)]
public SuperPower PrimarySuperPower { get; set; }
public SuperPower SecondarySuperPower { get; set; }
【问题讨论】:
-
属性如何知道它附加到什么?属性只是元数据。
标签: c# asp.net-mvc validation data-annotations