Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Success messages as opposed to model state error messages

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?

like image 538
Martin Avatar asked Jan 26 '10 22:01

Martin


People also ask

How do I add an error message in ModelState?

Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

What is AddModelError?

AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.


2 Answers

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>
<% } %>
like image 192
Rosstified Avatar answered Oct 12 '22 13:10

Rosstified


I suppose you could check the modelstate and set a variable in your model...

public ActionResult MyAction(MyEntity model)
{
  //Here would be some validation, which returns with ModelState errors

  //Now set the validity of the modelstate as the IsValid property in your entity
  model.IsValid = ModelState.IsValid;

  return View(model);
}

In your view...

<% if(Model.IsValid) { %>
  <p>You successfully transfered your balance to your ex.</p>
<% } %>

Edit: Given your updated question, I think you're looking at taking the wrong approach. I would go along with the other answers and follow a PRG pattern. This definitely makes more sense than trying to add a fake error.

like image 43
Dan Atkinson Avatar answered Oct 12 '22 13:10

Dan Atkinson