Merge ViewModel

巧了我就是萌 提交于 2020-01-05 09:07:37

问题


Im starting MVC & would like your advice about Repositories & View models, specifically combining a few sets of repository data into one VM.

If I have a web page with three distinct sections (columns) that require their own repositories (sorry for the basic nature of this):

UserInfoData - shown in Left col

DiaryData - shown in Middle col

CommentData - Shown in Right col

Im doing the following :-

public ActionResult Index(int id)
{
  UserInfoData uid = repository.GetUserInfoData(id);
  UserInfoDataVM UserViewModel = Mapper.Map<UserInfoData, UserInfoDataVM>(uid);

  //RETRIEVE DiaryData & CommentData using same principle as above

  return ??
}

How would I combine these three VM's into something I can return to the view - do I use another VM which accepts these three VM's?

Is there a best practice when dealing with smaller segments of a web page that have their own data?


回答1:


In my opinion, it depends on your usage scenario.

You could create a View Model that contains the three sub view models, but you would need to ask yourself, am I going to use any of the three sub view models anywhere else? If not, then you could just use one large view model. Else, there is nothing wrong with the 'wrapper' view model that encapsulates smaller view models.

You could keep the three view models as you have defined above and you could use the Html.RenderAction syntax in your view to actually go and fetch each of the sub parts of your page. You would have defined an action on your controller whose responsibility it is to populate each of the small view models and return the view for that model.

<div id="leftCol">
   @{Html.RenderAction("LeftCol", "Controller");}
</div>
<div id="midCol">
   @{Html.RenderAction("MiddleCol", "Controller");}
</div>
<div id="rightCol">
   @{Html.RenderAction("RightCol", "Controller");}
</div>

This would give you the ability to use the sub parts anywhere on your site and you only have to define the action method and partial views once.

The second option is also a personal favorite because you can quickly leverage JQuery to do partial page loading if these sections take a few seconds to populate and render (if this makes sense for your page). Now, your page opens quickly, you have a JS function that goes and fetches these sections, put a little loading graphic over them and are loaded/rendered using an AJAX request. Again, only if this makes sense for you, but using the Partial Views/Render action methods typically give you more flexibility in reuse across the site and AJAX partial page rendering.



来源:https://stackoverflow.com/questions/9547810/merge-viewmodel

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