ASP.NET MVC: How to display success confirmation message after server-side processing

I Would use TempData["key"]

This is like ViewData["key"] however the data persists for the next HttpRequest and is disposed automatically by asp.net after this

So you can do this.

Controller Action

[HttpPost]
public ActionResult SomePostAction(SomeViewModel vm)
{
   if(ModelState.IsValid) // Is User Input Valid?
   {
       try
       {
           CommitData();
           TempData["UserMessage"] = new MessageVM() { CssClassName = "alert-sucess", Title = "Success!", Message = "Operation Done." };
           return RedirectToAction("Success");
       }
       catch(Exception e)
       {
           TempData["UserMessage"] =  new MessageVM() { CssClassName = "alert-error", Title = "Error!", Message = "Operation Failed." };
           return RedirectToAction("Error");
       }

   }

   return View(vm); // Return View Model with model state errors
}

_Layout.cshtml

<!DOCTYPE html>
   <html>
     <head>

     </head>
     <body>
      @if(TempData["UserMessage"] != null)
      { 
          var message = (MessageVM)TempData["UserMessage"];
          <div class="alert @message.CssClassName">
               <strong>@message.Title</strong> 
               @message.Message
          </div>
      }
          @RenderBody()
     </body>
</html>

More Info: http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html


On a successful operation ,you just store the success message description into ViewBag like as

ViewBag.successMessage="Success" 

then in view check the ViewBag value is null or not? through javascript ,if not null show the message in Div

if('@ViewBag.successMessage'!="")
{
   $('#divSuccessMessage').show();
} 
else
{
  $('#divSuccessMessage').hide();
}

default in page load hide the div