【问题标题】:How to send Model to _Layout.cshtml (I need to send another model to Index view too)如何将模型发送到 _Layout.cshtml(我也需要将另一个模型发送到索引视图)
【发布时间】:2015-08-08 19:44:05
【问题描述】:

我需要发送两个不同的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 的方式相同。

【问题讨论】:

  • 为什么不用模型创建局部视图并在布局中渲染。
  • 听起来不错,但我更喜欢没有这个解决方案,有没有办法将模型直接发送到_layout?
  • 使用局部视图或子操作。很多例子——见hereherehere...
  • 请再看一遍问题,我想发给index viewpartial view两个人!!!

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


【解决方案1】:

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

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

@{ Html.RenderAction("_widget", "Home"); }

【讨论】:

  • 我们不能在 _Layout.cshtml 中使用 RenderAction。它导致递归调用
【解决方案2】:

您需要将其发送到 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 的第二个答案重复但经过改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2018-08-17
    • 2023-02-14
    • 1970-01-01
    • 2011-05-26
    相关资源
    最近更新 更多