4

在我的控制器中,我根据用户首先选择的参数过滤列表。它就像一个搜索引擎。

该列表有可能返回 0 值。虽然这不是错误,但我想显示某种消息,例如错误消息,但到目前为止我发现的只是在 c# 中使用 ModelState 或 ModelStateDictionary,这也需要异常。但这也不例外,只是一个条件,所以我有点疑惑。

我将写出一些代码,以便您直观地看到我想要的内容:

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

对,这就是我想做的事情。我该如何继续?感谢您的建议。

4

2 回答 2

5

ModelState 不需要例外。您可以使用任何您想要的消息添加 Modelstate 错误,并使用常规方法检查 ModelState.isValid 以决定是继续还是返回视图以显示错误。

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

或者,您也可以使用ViewBagViewData隐藏消息。

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

然后在视图中它们可以显示

@Html.ValidationMessage("ModelName")
@ViewData["ErrorMessage"]
@ViewBag.ErrorMessage
于 2013-02-12T20:47:41.383 回答
3

如果您没有传递 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>
}
于 2015-10-12T18:06:03.583 回答