Reputation: 882
I'm tring to find a good approach to feedback messages after a POST.
for example, I have these methods
public ActionResult Index(int id)
{
Model model = getModel(id);
return View(model);
}
[HttpPost]
public ActionResult Save(Model model)
{
Result result = saveModel(result)
if (Result.Status != Status.SUCCESS)
{
...
}
else if(Result.Status != Status.FAILURE)
{
...
}else
{
...
}
return RedirectToAction("Index");
}
and Result class has a message property
public class Result
{
...
public string Message{get;set;}
}
So, When I call .../Controller/Index/1 my index view is shown and this view has an submit button that call Save Action, but if something goes wrong on business layer, I would like to present error/warning message.
so, the doult is What is the best approach to solve this situation?
I have read some article that recommend TempData, others recommend ViewData, to transfer the message to Index View.
Upvotes: 3
Views: 4220
Reputation: 4681
Let me share an example of a ChangePassword action of one project that I developed:
[HttpPost]
public ActionResult ChangePassword(LoginModel model)
{
if (ModelState.IsValid && _userService.ChangePassword(model.Password, model.NewPassword))
ViewBag.SuccessMessage = UI.PasswordChanged;
else
ModelState.AddModelError("Password", ErrorMessages.InvalidPassword);
return View(model);
}
Just remember that ViewBag wont work if you are redirecting to another action. You must use TempData if you want to persist the information across one request.
Upvotes: 6
Reputation: 101130
For failures you should use
ModelState.AddModelError("", "The error message");
since it will automatically be picked up by Html.ValidationSummary(true)
(which is automatically added to all views)
For notifications you can use either TempData
or the ViewBag
.
I however discourage you from redirecting for everything. Instead give the user a chance to correct any errors (even if it's the business layer which generates them). Use something like:
[HttpPost]
public ActionResult Save(Model model)
{
if (!ModelState.IsValid)
return View(model);
Result result = saveModel(result)
if (Result.Status == Status.SUCCESS)
return RedirectToAction("Index");
if (Result.Status != Status.FAILURE)
{
ModelState.AddModelError("", "Ooops, failed");
}
else
{
ModelState.AddModelError("", "Some other error");
}
return View(model)
}
Upvotes: 2