Thursday, May 12, 2016

ASP.Net MVC HTTP POST Controller Action Processing Pattern

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(SomeModel model, FormCollection collection)
{
try
{
if (!ModelState.IsValid)
{
// re-populate lookup (Select) lists, if necessary
//   Helper.SetLookupLists(model);
return View("Add", model);
}
else
{
// Helper class to process posted data
var process = new AddProcess(this.HttpContext);
process.Execute(model);  // throws exception if there is a problem
// Success - Redirect
return RedirectToAction("AddConfirmation", new
{
Id = model.Id,
Name = model.Name
});
}
}
catch (Exception ex)
{
// re-populate lookup (Select) lists, if necessary
//   Helper.SetLookupLists(model);
ModelState.AddModelError("", ex.Message);
return View("Add", model);
}
}