繁体   English   中英

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

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

我有一个列表框,如下所示:

 @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" })

我遇到的问题是,即使未选择任何成员,它也不会显示验证消息。

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

如果您在参考源中选中RequiredAttribute ,您将看到如下重写的IsValid方法:

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

    // other stuff

    return true;
}

这里的问题是IsValid方法仅检查空值和空对象,而不检查集合对象(例如IEnumerable<T>存在的Count属性。 如果要检查零值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; }
}

注意:

使用int[]数组类型代替List<int>例如public int[] Members { get; set; } public int[] Members { get; set; } public int[] Members { get; set; }应该适用于标准RequiredAttribute因为当未选择任何项目时,数组属性返回null ,而List<T>属性调用默认构造函数,该构造函数将创建一个空列表。

相关问题:

通用列表属性的必需属性

暂无
暂无

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

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