Success message from Controller to View
asp.net, asp.net-mvc-4, c#, notifications
Solution
There are a few ways to skin this cat. You could use the ViewBag:
ViewBag.SuccessMessage = "<p>Success!</p>";
Then in your view you could render it to the page:
@ViewBag.SuccessMessage
I'm not a fan of the ViewBag, so I typically have a ViewModel object created that holds all the data I would need for my particular view. And a success message would be just that kind of data:
public MyViewModel{
public bool IsSuccess {get;set;}
}
Then in your controller, you would pass this ViewModel to your stongly-typed view
[HttpPost]
public ActionResult Update(MyViewModel vm){
//Glorious code!
return View(vm)
}
Finally, just check it in your view and print a message if it succeeds:
@if(vm.IsSuccess){
<p>Here is an amazing success message!</p>
}
Also, instead of that, you can use TempData, which works like the ViewBag but only lasts until the end of your next request and is then discarded:
TempData["SuccessMessage"] = "Success!";
Problem
The goal I want to display in my view some message when some user is added. The problem When something goes wrong in our model, there is a method (`ModelState.AddModelError`) to handle unsuccessful messages. But, when the things go okay, how can we handle a message to the user saying that his action was a success? I found this thread that provides a solution, but about three years passed and I need to know: there's not another way, perhaps more mature? Not that this is not, but we still deal with messages of success on this same way?