1

我需要发送 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.

4

2 回答 2

3

您可以将其放置在您的布局中以每次加载部分内容...对于在每个页面上加载动态菜单或小部件非常有用。

除了布局中的这一行之外,您还可以像往常一样制作索引页面。

@{ Html.RenderAction("_widget", "Home"); }
于 2016-03-09T21:47:48.047 回答
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的第二个答案重复但精炼。

于 2016-03-09T21:24:22.993 回答