簡體   English   中英

如何在ASP.NET Core MVC中顯示特定的ModelState錯誤?

[英]How to display specific ModelState errors in ASP.NET Core MVC?

在我的一個控制器動作中,我要做的第一件事是將模型傳遞給新動作,該動作實際上只是解析輸入以確定用戶是否輸入了有效日期。 然后返回模型,並檢查ModelState.IsValid。

public Import ValidateUploadModel(Import Model)
    {
        // DO not allow future dates
        if (Model.CurrMoInfo.CurrMo > DateTime.Now)
        {
            ModelState.AddModelError("FutureDate", "You cannot assign a future date.");
        }
        //Do not allow dates from the same month (we run the processing a month behind)
        if (Model.CurrMoInfo.CurrMo.Month == DateTime.Now.Month)
        {
            ModelState.AddModelError("SameMonth", "You must process a previous month.");
        }

        //Ensure day is last day of a previous month
        if (Model.CurrMoInfo.CurrMo.Day != DateTime.DaysInMonth(Model.CurrMoInfo.CurrMo.Year, Model.CurrMoInfo.CurrMo.Month))
        {
            ModelState.AddModelError("LastDay", "You must enter the last day of the month.");
        }

        //Do not allow dates older than 12 months back
        if (Model.CurrMoInfo.CurrMo < DateTime.Now.AddMonths(-12))
        {
            ModelState.AddModelError("TooOld", "Date must not be older than a year.");
        }

        return Model;
    }

在知道存在模型狀態錯誤的那一點上,我可以通過以下內容在剃刀視圖中正確顯示它們

<span class="text-danger">@Html.ValidationSummary(false)</span>

因此,由於我所有的模型狀態錯誤都是針對頁面上的相同輸入的,因此我可以放心地這樣做。 但是,如果我有需要相互獨立顯示的各種輸入和各種錯誤,該怎么辦? 我將如何去做呢? 另外,除了使用@ Html.ValidationSummary之外,還有其他更好(或更合適)的方法嗎?

我搜索了Microsoft文檔和數十個StackOverflow問題,以嘗試將較舊的答案轉換為.Net Core。

為清楚起見進行編輯:

這是剃刀視圖中的整個卡片:

<div class="card-body">

                @if (Model.StagingCount == 0)
                {
                    <input asp-for="@Model.CurrMoInfo.CurrMo" type="date" required class="col-lg-12" />
                }
                else
                {
                    <input asp-for="@Model.CurrMoInfo.CurrMo" type="date" disabled="disabled" required class="col-lg-12" />
                }

                <span class="text-danger">@Html.ValidationSummary(false)</span>

            </div>

輸入是針對模型屬性的,但未添加注釋。 我編寫了自己的規則,如果不遵守規則,則將錯誤手動添加到模型狀態。 我擁有的代碼有效,但是當我開始需要驗證更多字段時,它無法擴展。 我只想知道這樣做的更好方法。

在上面的示例中,您並沒有真正遵循標准慣例。

對於像這樣的簡單驗證(您僅在一個字段中驗證值),用於將錯誤消息放置在ModelState中的鍵應該與模型中受影響字段的名稱相同。 在您的情況下,實際上所有錯誤均應根據CurrMoInfo.CurrMo鍵記錄。 僅錯誤消息本身需要有所不同。 據我所知,對每個特定的不同錯誤使用自定義鍵不會為您的應用程序增加任何價值。 您沒有按預期方式使用它。

如果將它們全部記錄在CurrMoInfo.CurrMo則可以使用asp-validation-for標簽助手來創建一個字段,該字段專門顯示該字段的錯誤,例如

<span asp-validation-for="CurrMoInfo.CurrMo" class="text-danger"></span>

然后,您可以(可選)使用ValidationSummary(如標題所示)匯總整個模型的所有錯誤-並顯示您可能創建的與單個特定字段無關的任何其他模型錯誤。

完整的例子:

public Import ValidateUploadModel(Import Model)
{
    // DO not allow future dates
    if (Model.CurrMoInfo.CurrMo > DateTime.Now)
    {
        ModelState.AddModelError("CurrMoInfo.CurrMo", "You cannot assign a future date.");
    }
    //Do not allow dates from the same month (we run the processing a month behind)
    if (Model.CurrMoInfo.CurrMo.Month == DateTime.Now.Month)
    {
        ModelState.AddModelError("CurrMoInfo.CurrMo", "You must process a previous month.");
    }

    //Ensure day is last day of a previous month
    if (Model.CurrMoInfo.CurrMo.Day != DateTime.DaysInMonth(Model.CurrMoInfo.CurrMo.Year, Model.CurrMoInfo.CurrMo.Month))
    {
        ModelState.AddModelError("CurrMoInfo.CurrMo", "You must enter the last day of the month.");
    }

    //Do not allow dates older than 12 months back
    if (Model.CurrMoInfo.CurrMo < DateTime.Now.AddMonths(-12))
    {
        ModelState.AddModelError("CurrMoInfo.CurrMo", "Date must not be older than a year.");
    }

    return Model;
}


<div class="card-body">
    @if (Model.StagingCount == 0)
    {
        <input asp-for="CurrMoInfo.CurrMo" type="date" required class="col-lg-12" />
    }
    else
    {
        <input asp-for="CurrMoInfo.CurrMo" type="date" disabled="disabled" required class="col-lg-12" />
    }
    <span asp-validation-for="CurrMoInfo.CurrMo" class="text-danger"></span>
</div>

進一步閱讀: https : //docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/validation?view=aspnetcore-2.2

附言:我不認為此一般原則已從.NET Framework更改為.NET Core。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM