简体   繁体   English

如果未选择任何项目,则ListBoxFor不显示ValidationMessageFor

[英]ListBoxFor not showing ValidationMessageFor if no items are selected

I have a listboxfor as shown below: 我有一个列表框,如下所示:

 @Html.Label("Members", htmlAttributes: new { @class = "control-label required", @multiple = "multiple" })
 @Html.ListBoxFor(model => model.Members, (IEnumerable<SelectListItem>)ViewBag.Members, new { @class = "form-control", @multiple = "multiple" })                                               
 @Html.ValidationMessageFor(model => model.Members, "", new { @class = "text-danger" })

The problem that I am experiencing is that it does not show the validation message even if no member has been selected. 我遇到的问题是,即使未选择任何成员,它也不会显示验证消息。

    [Required(ErrorMessage = "Please select a member")]
    public List<int> Members { get; set; }

If you check RequiredAttribute in reference source , you will see overriden IsValid method like this: 如果您在参考源中选中RequiredAttribute ,您将看到如下重写的IsValid方法:

public override bool IsValid(object value) 
{
    // checks if the object has null value
    if (value == null) 
    {
        return false;
    }

    // other stuff

    return true;
}

The problem here is IsValid method only checks for null values & null objects, but does not check Count property which exists in collection objects eg IEnumerable<T> . 这里的问题是IsValid方法仅检查空值和空对象,而不检查集合对象(例如IEnumerable<T>存在的Count属性。 If you want to check against zero-valued Count property (which indicates no selected items), you need to create custom annotation attribute inherited from RequiredAttribute containing IEnumerator.MoveNext() check and apply it to List<T> property: 如果要检查零值Count属性(指示没有选中的项目),则需要创建从包含IEnumerator.MoveNext()检查的RequiredAttribute继承的自定义注释属性,并将其应用于List<T>属性:

[AttributeUsage(AttributeTargets.Property)]
public sealed class RequiredListAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IEnumerable;

        // check against both null and available items inside the list
        return list != null && list.GetEnumerator().MoveNext();
    }
}

// Viewmodel implementation
public class ViewModel
{
    [RequiredList(ErrorMessage = "Please select a member")]
    public List<int> Members { get; set; }
}

Note: 注意:

Using int[] array type instead of List<int> eg public int[] Members { get; set; } 使用int[]数组类型代替List<int>例如public int[] Members { get; set; } public int[] Members { get; set; } public int[] Members { get; set; } should work for standard RequiredAttribute because array property returns null when no items are selected, while List<T> properties call default constructor which will create an empty list. public int[] Members { get; set; }应该适用于标准RequiredAttribute因为当未选择任何项目时,数组属性返回null ,而List<T>属性调用默认构造函数,该构造函数将创建一个空列表。

Related issue: 相关问题:

Required Attribute on Generic List Property 通用列表属性的必需属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM