复杂类型的可选[必需]

时间:2012-01-17 15:05:52

标签: asp.net-mvc-3 data-annotations

我正在尝试将我的viewmodel设置为一个表单,该表单将收集有关加入团队的人员的信息。表单必须包含一些引导信息,然后是5个“团队成员”列表(每个包含一个名称,电子邮件和电话),前两个将是必需的。对于我的验证,我希望它在各个领域,如下:

Person 1:
Name: (validation messaage)
Email: (validation message)
Phone: (validation message)

Person 2:
Name: (validation messaage)
Email: (validation message)
Phone: (validation message)

Person 3:
Name: 
Email:
Phone:

Person 4:
Name: 
Email:
Phone:

Person 5:
Name: 
Email: 
Phone: 

我的viewmodel的相关部分目前是:

[Required]
public TeamMember TeamMember1 { get; set; }

[Required]
public TeamMember TeamMember2 { get; set; }

public TeamMember TeamMember3 { get; set; }

public TeamMember TeamMember4 { get; set; }

public TeamMember TeamMember5 { get; set; }

所以在我看来,我只写:

@Html.EditorFor(model=>model.TeamMember1)

@Html.EditorFor(model=>model.TeamMember2)

@Html.EditorFor(model=>model.TeamMember3)

@Html.EditorFor(model=>model.TeamMember4)

@Html.EditorFor(model=>model.TeamMember5)

编辑器模板如下所示:

@model MyProject.Models.TeamMember

<div class="editor-label">
    @Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Phone)
    @Html.ValidationMessageFor(model => model.Phone)
</div>

很抱歉在一个帖子中投入了太多,但有没有人建议如何最好地设置它?我考虑过从RequiredAttribute继承并替换TeamMember属性上的[Required],但我不确定如何在子字段上设置验证消息。现在,即使它是空的,它也会通过所需的检查,我假设因为对象是绑定的(因此不是null),即使所有属性都是空的。

感谢任何反馈。

1 个答案:

答案 0 :(得分:1)

您可以编写自定义验证程序。下面是如何访问其他属性值的示例。然后,您可以使用此自定义装饰TeamMember或属性 验证属性取决于验证逻辑。我会在班级推荐它

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    //Retreive value of Name property
    var nameProperty = validationContext.ObjectType.GetProperty("Name");
    var namePropertyValue = (string)nameProperty.GetValue(validationContext.ObjectInstance, null);

    var propertyBeingValidatedValue = (string)value;

    //Validation logic
    if ((!string.IsNullOrEmpty(propertyBeingValidatedValue)) && (!string.IsNullOrEmpty(namePropertyValue)))
    {
        //returning null means everything is good.
        return null;
    }
    //return a message in any other case.
    return new ValidationResult("Validation Message");
}