asp.net mvc controller post best practices

喜夏-厌秋 提交于 2019-12-06 06:38:10

This depends if you expect and plan to deal with exceptions.

My usual approach is:

public ActionResult foobar(FormCollection formCollection)
{
    //Keep this out of the try catch scope in case you need to pass it
    // to the next method.
    Model model = new Model();

    try
    {
        if(!TryUpdateModel(model)
        {
            //Update Failed so fix it and redirect
            return redirectToAction("fixit");
        }
        if(!ModelState.IsValid())
        {
            //Update worked but model state was invalid, return to page to correct 
            //model validation errors
            return View("foobar", model);
        }
        //Update Succeeded so do other stuff
    }
    catch(Exception ex)
    {
        //Deal with Exception
        return redirectToAction("ErrorView", "ErrorController");
    }

    return redirectToAction("NextStep");
}

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:

[HttpPost]
public ActionResult Edit(ReportViewModel reportViewModel)
{
    if (!ModelState.IsValid)
    {
        // there were validation errors => redisplay the form
        // so that the user can fix them
        return View(reportViewModel);
    }

    // At this stage the view model is valid => we can
    // map it back to a domain model and pass to the repository 
    // for processing

    // Fetch the domain model that we want to update
    var report = _repository.Get(reportViewModel.Id);

    // map the domain model properties from the view model properties
    // in this example I use AutoMapper
    Mapper.Map<ReportViewModel, Report>(reportViewModel, report);

    // perform update
    _repository.Update(report);

    // the update wen fine => we can redirect back to the list action
    return RedirectToAction("List");
}

So, as you can see no FormCollection, no TryUpdateModel, no UpdateModel, no try/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."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!