簡體   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