Passing a ViewModel to a Partial View call in the

2019-06-13 00:37发布

问题:

BACKGROUND

I am trying to make use of Dashboard template on an MVC application I'm working on.

I am not sure how I can pass a ViewModel to the top bar I've called Header.

CODE

In my _Layout.cshtml, I have split the HTML like so:

<body class="">
  @Html.Partial("_Header")

  <div class="page-container row-fluid">
    @Html.Partial("_Sidebar")

    <div class="page-content">
      <div class="content">
        @RenderBody()
      </div>
    </div>
  </div>
</body>

I am guessing this is wrong because now I cannot pass a ViewModel to the header section, or if I can, we're not supposed to?

What is the right way of splitting this?

回答1:

Instead of @Html.Partial(), use @Html.Action() or @{ Html.RenderAction(); } to call a [ChildActionOnly] controller methods that initializes your model for the dashboard and returns a partial view, for example

[ChildActionOnly]
public PartialViewResult Header()
{
    // initialize a model
    return PartialView("_Header", model)
}

and in the layout

@{ Html.RenderAction("Header", yourControllerName); }

The alternative is that the model you use in each view using that layout would need a property which is the model used to generate your dashboard and then use @Html.Partial("_Header", Model.yourDashBoardProperty)