如何将Model发送到_Layout.cshtml(我还需要将另一个模型发送到Index视图)

时间:2015-08-08 19:44:06

标签: asp.net-mvc-5 asp.net-mvc-partialview asp.net-mvc-layout

我需要发送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);
}

我不喜欢使用ViewBagViewData& ...,我正在寻找以将模型传递给Views的方式传递模型。

2 个答案:

答案 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

相关问题