必选的现场验证有选择地工

时间:2017-03-24 15:46:05

标签: c# asp.net-mvc data-annotations

我有一个有两个字段的视图。必需的字段验证适用于一个,而不适用于另一个。我错过了什么吗?

不工作:

<div class="form-group">
                    <div class="controls">
                        <label class="control-label" for="Selected Organizations">Selected Organization(s)</label>
                        <div class="panel panel-default">
                            <div class="panel-body" style="overflow-y: auto; max-height: 100px; min-height:50px" id="divSelOrgs">
                                @for (int i = 0; Model.Organizations != null && i < Model.Organizations.Count(); i++)
                                {
                                    var org = Model.Organizations[i];
                                    var checkedAttr = (org.Id != Guid.Empty) ? "checked='checked'" : "";
                                    <div class="row">
                                        <input type="hidden" name="Organizations.Index" value="@i" />
                                        <input type="hidden" name="Organizations[@i].Name" value="@org.Name" />
                                        <input type="hidden" name="Organizations[@i].Data" value="@org.Data" />
                                        <div class="col-xs-1">
                                            <input type="checkbox" name="Organizations[@i].Id" value="@org.Id" @checkedAttr data-org-selected="true" />
                                        </div>
                                        <div class="col-xs-11" data-toggle="tooltip" data-placement="top" title="@org.Data">@org.Name</div>
                                    </div>
                                }
                            </div>
                        </div>
                        @Html.ValidationMessageFor(m => m.Organizations)
                    </div>
                </div>

工作:

<div class="form-group">
                @Html.LabelFor(m => m.FirstName, new { @class = "control-label" })
                @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", placeholder = "First name" })
                @Html.ValidationMessageFor(m => m.FirstName)
</div>

型号代码:

 [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
 [Required(ErrorMessage = "The {0} field is required.")]
    [Display(Name = "Selected Organization(s)")]
    public List<OrganizationDTO> Organizations { get; set; }

1 个答案:

答案 0 :(得分:1)

dataannotation不适用于list类型,但您可以custom attributevalidation验证列表

public class RequiredListAttribute : ValidationAttribute
{
    public override bool IsValid(object list)
    {
        var list = list as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}

,您的财产将是

[RequiredList(ErrorMessage = "The field is required.")]
public List<OrganizationDTO> Organizations  { get; set; }