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?
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 .
AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.
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>
<% } %>
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.
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