开发者

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开发者_C百科 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?


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.


You should implement something like the 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);

(note: doesn't actually redirect, see comments)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜