Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an error message under certain conditions (empty list)

Tags:

c#

asp.net-mvc

In my controller, I filter a list based on parameters that the user first choose. It's like a search engine.

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

I will write out a bit of code so that you will visually see what I want:

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

Right, that about what I want to do. How could I proceed? Thanks for the advices.

like image 492
hsim Avatar asked Feb 18 '23 13:02

hsim


2 Answers

ModelState doesn't require an exception. You can just add a Modelstate error with whatever message you want and use the normal method for checking the ModelState.isValid to decide whether to proceed, or return to the view to show the error.

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

Alternatively, you could use ViewBag or ViewData to hole 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
like image 164
Forty-Two Avatar answered Apr 05 '23 23:04

Forty-Two


If you are not passing Model and don't want to check with ModelState you can just pass any messages to ViewBag and check in the view for value of it. If it's there then show 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>
}
like image 43
Vlad Bezden Avatar answered Apr 05 '23 22:04

Vlad Bezden