Success messages as opposed to model state error messages

Martin picture Martin · Jan 26, 2010 · Viewed 12.9k times · Source

For error messages, validation faults etc you have

ModelState.AddErrorMessage("Fool!");

But, where do you put success responses like "You successfully transfered alot of money to your ex." + "Your balance is now zero". I still want to set it at the controller level and preferably in key-value way, the same way as errormessages but without invalidating the modelstate.

How is this usually done? ViewData?

Answer

Rosstified picture Rosstified · Jan 27, 2010

I would populate TempData["success"] (or what ever key you want to give it) with the message I want to display within the controller, then redirect appropriately (e.g. if I edit a user, I redirect back to the user list). This relies on POST/Redirect/GET pattern - which is a good practice anyway.

TempData["success"] = "Your Balance is now zero";

In the master page I have a section that checks that variable and displays the message in a nice styled div. Something like (may not be 100% correct):

<% if(TempData["success"] != null) { %>
      <div id="SuccessMessage"><%= Html.Encode(TempData["success"]) %><div>
<% } %>