如何使用可重用模板包装控制器的所有视图?

时间:2016-06-18 19:08:38

标签: html asp.net-mvc view controller dry

我有一个ASP MVC 5应用程序,它有一个名为Member的控制器,其中包含所有与成员相关的操作和视图。通过此控制器创建的所有视图都应包含在一个用作菜单的html中。例如,欢迎视图可能如下所示:

<div class="member-menu">
    <!-- View code goes here -->
    <p>Welcome</p>
</div>

虽然另一种观点可能如下:

<div class="member-menu">
    <!-- View code goes here -->
    <p>Some other stuff here</p>
</div>

如果可能的话,我希望避免在每个视图中重复菜单代码,因为它将来可能会变大。我已经对共享视图,子操作和自定义路由进行了一些研究,但似乎无法找到适合此模式的任何内容。我想在这里做的很容易吗?

1 个答案:

答案 0 :(得分:1)

For this specific task, it looks like you need a Layout

MenuWrapperTemplate.cshtml

<div class="member-menu">
    @RenderBody();
</div>

Welcome view

@{
    Layout = "~/Views/Shared/MenuWrapperTemplate.cshtml";
}
<!-- View code goes here -->
<p>Welcome</p>

If these are really menus, are you want them in the site's layout/master then take a look here MVC where to render menu view

You probably should get to grips with MVC, and the Html helpers (Render/RenderAction/partial) and how layouts work.

Hope that helps