Display error message under certain conditions (empty list)

In my controller, I am filtering the list based on the options the user selects first. It's like a search engine.

There is a possibility that the list may return 0 values. While this is not a bug, I would like to display some kind of message like an error message, but all I have found so far is using a ModelState or ModelStateDictionary in C # which also requires an exception. But this is no exception, just a condition, so I'm a little puzzled.

I'll write some code so you can visually see what I want:

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

      

That's right, this is about what I want to do. How can I proceed? Thanks for the advice.

+3


source to share


2 answers


ModelState does not require an exception. You can simply add the ModelState error with any message you want and use the normal method to check ModelState.isValid to decide whether to continue or return to the view to show the error.

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

      

Alternatively, you can use ViewBag

or ViewData

to open the message as well.



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

      

Then in the view they can be displayed

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

      

+4


source


If you are not passing through the Model and do not want to check with ModelState, you can simply pass any messages to the ViewBag and check the view for its value. If it is there, then display it in the view.

Controller:

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
}

      



Index View

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

      

+1


source







All Articles