views:

446

answers:

3

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?

+2  A: 

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.

Dan Atkinson
Hey Dan, coming to my rescue again. This only gives me one possible response. I'll rephrase the question.
Martin
+1  A: 

You should implement POST/Redirect/GET pattern and redirect to another view at the end of your action methods after all validations were verified and everything executed fine. You can pass entire object instance to the destination view or you just pass plain text message, or you can pull out the text in the destination View itself from web.config or from Resource file.

For instance, I have one view in Shared folder named "ChangeSuccess.aspx" to which I redirect for all my successful edits&creates.

You redirect like this

return View("ChangeSuccess", objectInstance);

HTH

mare
+4  A: 

I populate TempData["success"] (or what ever key you want to give it) with the message I want to display within the controller, then redirect appropriatly (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"><%= Hmtl.Encode(TempData["success"]) %><div>
<% } %>
RM
if you dont want to use Post/Redirect/Get pattern, you can use ViewData rather than TempData to hold the value. I would very highly recommend using Post/Redirect/Get though...
RM
That makes alot of sense. Where do you learn stuff like that?
Martin