Domanda

I've been working for some time on an application and a slight problem arose.

I wonder how I could display error / results to the user upon any action undertaken.

Up to now here's how I proceeded with an example:

if(itemID == null)
{
    ViewData["ErrorMessage"] = "The ID provided provoked an error. Please try again. If the problem persist, contact your local administrator.";
}

Something extremely simple... if we consider that the user remains in the same view. Or there are many places in which I must redict the user using RedirectToAction("Action"), and that ViewData is then flushed.

So I am asking any MVC "wise-master" out there: do you have an efficient, re-usable way of displaying messages, may it be in any format? And could you explain sommarily how you would do it?

Thank you!

È stato utile?

Soluzione

If there's an error then, in general, the user should stay in the same view and not be redirected. So they can correct the error and try again. So you'd basically just do this:

if(itemID == null)
{
    ViewData["ErrorMessage"] = "The ID provided provoked an error. Please try again. If the problem persist, contact your local administrator.";
    return View(); // you probably have a model to include as well
}
else
{
    // perform your action
    return RedirectToAction("some action");
}

After all, just look at the error message you're displaying:

The ID provided provoked an error. Please try again. If the problem persist, contact your local administrator.

You might also consider using something like TempData which doesn't get flushed until it's used. Perhaps like this:

if(itemID == null)
{
    TempData["ErrorMessage"] = "The ID provided provoked an error. Please try again. If the problem persist, contact your local administrator.";
}

This will persist across redirects and will be available until after it's requested. So even if you send the user through some complex series of redirects, when a view eventually renders and checks for a value in TempData["ErrorMessage"] it will still be there. (And I think will be destroyed after it's read.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top