我需要发送2个不同的Models
,一个发送到Index view
,另一个发送到_Layout.cshtml
,我该怎么做?
我的HomeController
:
[Route("")]
public ActionResult Index()
{
HomeViewModel model = new HomeViewModel();
model.A = _repoA.GetLatest(4);
model.B = _repoB.GetLatest(4);
model.C = _repoC.GetLatest(4);
return View(model);
}
我不喜欢使用ViewBag
,ViewData
& ...,我正在寻找以将模型传递给Views
的方式传递模型。
答案 0 :(得分:3)
您可以将其放置在布局中以便每次加载部分...非常适合加载动态菜单或每个页面上的小部件。
除了你的布局中的这一行,你可以像往常一样做你的索引页面。
@{ Html.RenderAction("_widget", "Home"); }
答案 1 :(得分:1)
您需要在ViewBag中发送它。我发现最好的办法是制作一个抽象的控制器:
public abstract class ApplicationController : Controller
{
protected ApplicationController()
{
UserStateViewModel = new UserStateViewModel();
//Modify the UserStateViewModel here.
ViewBag["UserStateViewModel"] = UserStateViewModel;
}
public UserStateViewModel UserStateViewModel { get; set; }
}
然后,让所有控制器继承自这个抽象控制器。
在_Layout.cshtml(或其他任何名称)中,您需要在顶部包含以下内容:
@{
var userState = (UserStateViewModel)ViewBag.UserStateViewModel;
}
重复,但从第二个答案改为ASP.NET MVC Razor pass model to layout。