Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide success messages asp.net mvc?

Tags:

c#

asp.net-mvc

How do I provide success messages in asp.net mvc?

like image 861
mahesh Avatar asked Mar 04 '11 05:03

mahesh


Video Answer


2 Answers

If you're displaying a message on a different page than ViewData won't help you, since it's reinitialized with each request. On the other hand, TempData can store data for two requests. Here's an example:

public ActionResult SomeAction(SomeModel someModel)
        {
            if (ModelState.IsValid)
            {
                //do something
                TempData["Success"] = "Success message text.";
                return RedirectToAction("Index");
            }
            else
            {
                ViewData["Error"] = "Error message text.";
                return View(someModel);
            }
        }

Inside if block you must use TempData because you're doing redirection (another request), but inside else you can use ViewData.

And inside view you could have something like this:

@if (ViewData["Error"] != null)
{
    <div class="red">
        <p><strong>Error:</strong> @ViewData["Error"].ToString()</p>
    </div>
}
@if (TempData["Success"] != null)
{
    <div class="green">
        <p><strong>Success:</strong> @TempData["Success"].ToString()</p>
    </div>
}
like image 68
frennky Avatar answered Sep 30 '22 16:09

frennky


in your controller, you can do this:

ViewData["Message"] = "Success"

and in your view you you can check if there is a message to display, and if so than display it:

@if (ViewData["Message"] != null)
    <div>success</div>
like image 22
ItayMaoz Avatar answered Sep 30 '22 15:09

ItayMaoz