Reputation: 32808
I have action methods that do things like this:
productTable.AddOrUpdate(viewModel.Account);
I don't currently test for if it works. Is there an easy way I can check if this works and if it doesn't then give an error message and return to my view?
Upvotes: 1
Views: 1491
Reputation: 7448
This is not strictly related to MVC, I think it's a more general issue on how to design code properly to managed unexpected situations (or expected errors generated by user input) and giving appropriate feedback.
For unexpected behaviours we talk about Exception handling. You put your code in a try/catch block, and handle the exception in the catch.
For errors that may be generated by user input we're talking about validation. It means you check your object against a set of rules, and if one or more does not pass, you return a set of errors to your view and display it to the user.
Now for some MVC specific on how to do this. Let's have a bit of sample code:
[HttpPost]
[ModelStateToTempData]
public ActionResult SaveMyObject(MyObject myObject)
{
try
{
if (ModelState.IsValid)
{
MyRepository.Save(myObject);
return RedirectToAction("Success");
}
return RedirectToAction("MyForm");
}
catch (Exception ex)
{
//handle/log your exception as you see fit
ModelState.AddModelError("Name", "Message");
return RedirectToAction("MyForm");
}
}
In this sample we're assuming a few things:
This is a sample method that will receive the post of your form. The data comes from the modelbinder already validated. If the data is valid, you store it and redirect the user to the success page. If the data is not valid, you redirect him back to the actionmethod that diplays the form. Careful here: do not render the view directly from here: see the PRG pattern for a full explanation of this.
The whole thing is in a try/catch block so if something fails, you can trap/handle the error, and then add a custom error message to the page, then redirect the user to the actionmethod that renders the form and display the error to him.
Upvotes: 4