【发布时间】:2017-01-24 11:42:04
【问题描述】:
我(终于)从 WebForms 迁移到 MVC 并且出现了问题,似乎我找不到好的解决方案...
假设我在 _layout.cshtml 页面中有一个“小部件”,它显示登录用户的最后 4 条消息。这存在于网站的每个控制器中。
我应该如何进行?
a) BaseViewModel:对于每个控制器和每个操作,我必须创建从 BaseViewModel 继承的特定视图模型,并且在每个控制器中我设置数据 + baseviewModel 中的最后 4 条消息:
public ActionResult Index()
{
HomeViewModel h = new HomeViewModel();
h.UserName = "Daniele"; //in BaseViewModel
h.LastMessages = _messagesRepository.GetLastItems(4); //in BaseViewModel
//Other data specific to index page
return View(h);
}
public ActionResult Dashboard()
{
HomeViewModel h = new HomeViewModel();
h.UserName = "Daniele"; //in BaseViewModel
h.LastMessages = _messagesRepository.GetLastItems(4); //in BaseViewModel
//Other data specific to dashboard
return View(h);
}
b) Html Action: 似乎是一个更好的解决方案,但在每个控制器中我仍然需要复制和粘贴
[ChildActionOnly]
public PartialViewResult LastMessages()
{
//Code
}
在我将创建的每个控制器中。
最好的做法是什么?建议? 感谢您的帮助。
【问题讨论】:
-
您可以使用
Html.Action指定控制器 -
使用
[ChildActionOnly]方法,但它只需要在你的一个控制器中(比如MessagesController),然后在布局中使用@{ Html.RenderAction("LastMessages", "Messages"); }
标签: c# asp.net-mvc model-view-controller asp.net-mvc-5