I am bit confused about "best practice" controller using question.
My typically code look
public ActionResult Edit(int reportId,FormCollection formCollection)
{
try
{
var report = _dbContext.EmployeeReports.Find(reportId);
if (TryUpdateModel(report))
{
_employeeReportService.Update(report);
return RedirectToAction("List");
}
return View("Edit", report);
}
catch (Exception)
{
// some logging etc
return RedirectToAction("List");
}
Well, is better using "TryUpdateModel" or only "UpdateModel" or simple call Model.IsValid and is good idea to catch exception in controller?
Thanks
This depends if you expect and plan to deal with exceptions.
My usual approach is:
I try to use all of them in my code to try and catch every issue before it breaks something.
Here's an alternative way that I prefer:
So, as you can see no
FormCollection
, noTryUpdateModel
, noUpdateModel
, notry/catch
.After my opinion you should always use view models instead of formcollection to avoid under-posting and over-posting issues. Therefore best practice, after my opinion, is to use a view model for rendering the view and a kind of post/get model that binds to exactly what you want the users to post to/get from an action.
This might be some extra work and some of the view models will look quite similar to the models that you use for binding in controller action, but I would say "Security over convenience."