我需要发送两个不同的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一样。
发布于 2016-03-10 05:47:48
你可以把这个放在你的布局中,每次加载一个部分...在每个页面上加载一段动态菜单或一个小部件非常有用。
随着这行在您的布局,您可以只做您的索引页,您通常会这样做。
@{ Html.RenderAction("_widget", "Home"); }发布于 2016-03-10 05:24:23
您需要在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。
https://stackoverflow.com/questions/31897859
复制相似问题