How do I provide success messages in asp.net mvc?
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>
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With