如何将数据传递到我的布局PartialView? [英] How to pass data to a PartialView in my layout?
问题描述
我有一个包含此行一个_layout.cshtml:
I have a _layout.cshtml containing this row:
@{Html.RenderPartial("Menu");}
现在我想在一个模型传递到这个的RenderPartial功能。这种模式可以从我的资料库中读取。
Now I want to pass in a model into this RenderPartial-function. This model can be read from my repository.
如何以及在哪里(在code)可以这样做?
How and where(in code) can this be done?
谢谢!
推荐答案
的RenderPartial有,可以采取一个目的是将其发送给局部视图超载。
不要忘记在你partialview顶部的定义@model用正确的对象类型的工作。
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(视图名对象)
@Html.RenderPartial("ViewName",object)
额外的信息:<一href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.html.renderpartialextensions.renderpartial.aspx\"相对=nofollow> MSDN
评论后编辑:
我认为这将是更容易地创建一个MenuController这需要在库中。然后让它创建一个视图这需要在要求的资料库,因为它的模型,然后用一个foreach渲染每一个菜单项为actionlinks,通过菜单的信息吧。
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.
所以,你将有这你_layout.cshtml:
So you would have this in your _layout.cshtml:
<div id="Menu">
@{Html.RenderAction("Menu", "Menu");}
</div>
这在您的MenuController:
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);
}
}
和您的MenuView:
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?
这篇关于如何将数据传递到我的布局PartialView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!