簡體   English   中英

在特定條件下顯示錯誤消息(空列表)

[英]Display an error message under certain conditions (empty list)

在我的控制器中,我根據用戶首先選擇的參數過濾列表。 它就像一個搜索引擎。

列表有可能返回0值。 雖然這不是錯誤,但我想顯示某種消息,比如錯誤消息,但到目前為止我發現的所有消息都是在c#中使用ModelState或ModelStateDictionary,這也需要異常。 但這也不例外,只是一個條件,所以我有點困惑。

我會寫出一些代碼,以便您可以直觀地看到我想要的東西:

    if(listOBJS.count == 0)
    {
        // DISPLAY THE ERROR!
        PopulateDDL1();
        PopulateDDL2();
        return View(listOBJS);
    }

對,關於我想做什么。 我該怎么辦? 謝謝你的建議。

ModelState不需要例外。 您可以使用您想要的任何消息添加Modelstate錯誤,並使用常規方法檢查ModelState.isValid以決定是繼續,還是返回到視圖以顯示錯誤。

ModelState.AddModelError("", "Your Error Message");

或者,您也可以使用ViewBagViewDataViewBag消息。

ViewBag.ErrorMessage = "Your Error Message";
ViewData["ErrorMessage"] = "Your Error Message";

然后在視圖中可以顯示它們

@Html.ValidationMessage("ModelName")
@ViewData["ErrorMessage"]
@ViewBag.ErrorMessage

如果您沒有傳遞Model並且不想使用ModelState進行檢查,則可以將任何消息傳遞給ViewBag並在視圖中檢查它的值。 如果它在那里然后在視圖中顯示它。

控制器:

public FileResult Download(string fileName)
{
   if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
   {
       ViewBag.Error = "Invalid file name or file path";
       RedirectToAction("Index");
   }

   // rest of the code
}

索引視圖

@if (ViewBag.Error != null)
{
    <h3 style="color:red">@ViewBag.Error</h3>
}

暫無
暫無

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

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