How to pass data to a PartialView in my layout?

2019-08-08 16:31发布

问题:

I have a _layout.cshtml containing this row:

@{Html.RenderPartial("Menu");}

Now I want to pass in a model into this RenderPartial-function. This model can be read from my repository.

How and where(in code) can this be done?

Thanks!

回答1:

RenderPartial has an overload that can take an object to send it to the partial view. Don't forget to define your @model at the top of your partialview to work with the right object type.

@Html.RenderPartial("ViewName",object)

Extra info: MSDN

Edit after comment:

I think it would be easier to create a MenuController that takes in the repository. Then let it create a view which takes in the required repository as it's model, then with a foreach render every menu-item as actionlinks, passing the menu info to it.

So you would have this in your _layout.cshtml:

<div id="Menu">
    @{Html.RenderAction("Menu", "Menu");}
</div>

This in your MenuController:

public class MenuController : Controller
{
    private IMenuRepository _repository;

    public MenuController(IMenuRepository repo)
    {
        _repository = repo;
    }
    //
    // GET: /Menu/

    public PartialViewResult Menu(string menu = null)
    {
        ViewBag.SelectedMenu = menu;

        IEnumerable<MenuInfoObject> menus= _repository.Menus;
        return PartialView(menus);
    }
}

And your MenuView:

    @model IEnumerable<MenuInfoObject>
@{
    Layout = null;
}
@foreach (var item in Model)
{
    @Html.RouteLink(item.MenuName, new
{
    controller = item.ControllerInfo,
    action = item.ActionInfo,
}, new
       {
           @class = item.Menu == ViewBag.SelectedMenu ? "selected" : null
       })
}

Would that be any closer to a solution?



回答2:

There is another solution as well to pass data to a partial view in Layout. You can simply add this in your _Layout.cshtml file

@Html.Action("ActionName","ControllerName")

And in your Controller :

    [ChildActionOnly]
    public ActionResult ActionName()
    {
        var model = new YourModel();
        return PartialView(model);

    }

The ChildActionOnly attribute ensures that an action method can be called only as a child method. This action will render the corresponding partial view with model in Layout.