Hydrating ViewModels in ASP.NET MVC

我们两清 提交于 2019-12-04 11:19:11

Some general tips. Data can be separated into several categories: system-scope, session-scope, request-scope.

System scope data is data that needs to be presented to the user but is the same for each user. An example for a blog application would be a tag cloud, or a list of categories. I would argue that this data doesn't need to flow through the controller or action because it has nothing to do with user interaction. The View itself can call a HtmlHelper (or a LayoutDataHelper) that knows how to get (and preferably cache) this data.

Session scope data can be handled with ActionFilters that populate fields on the ViewData.Model. It is not directly related to the parameters of the action. For example, username. I prefer an attribute of the form

public class SessionDataFilter : ActionFilter 
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            var view = filterContext.Result as ViewResult;

            // hydrate session data on view.ViewData.Model
        }
    }
}

Everything else that is request-scope/specific must be populated in the Action. However, this doesn't mean you have to have one massive action method to do it. I would look at how your ViewModels are composed. As you suggested, if you have controls that need populating, it's likely that the information in the ViewModel can be grouped into related sets.So you might have a ViewModel that just composes other smaller view models ("partial view models"). I would then decompose the logic to populate each partial view model (and any other complex logic) each into its own re-usable and isolated method.

Similar abstraction applies when dealing with posts, though I would worry about the usability of pages that post lots of unrelated data. You should be able to use ActionFilters (OnActionExecuting) to parse related sets of incoming data (and optionally validating) and assign them to action parameters. I prefer filters over binders for posted data unless the same set of data is posted to multiple actions and the shape of the incoming data is always the same.

Good luck.

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