asp.net-mvc ASP MVC 3 在不同的视图中使用不同的布局
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5059323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP MVC 3 use different Layouts in different views
提问by Adam
I have an ASP MVC application which needs multiple different layouts. In ASP.NET Web Apps I would have just made separate master pages. How do I do this in ASP MVC 3?
我有一个需要多种不同布局的 ASP MVC 应用程序。在 ASP.NET Web Apps 中,我会制作单独的母版页。我如何在 ASP MVC 3 中做到这一点?
So far I have made a separate Layout.cshtml file for each layout I need.
到目前为止,我已经为我需要的每个布局制作了一个单独的 Layout.cshtml 文件。
I tried setting the layout in the view but it is getting blown away from the ViewStart.cshtml which is setting it back to the default layout for the site.
我尝试在视图中设置布局,但它从 ViewStart.cshtml 中被吹走了,它正在将其设置回站点的默认布局。
Also, I can't seem to get intellisense working with Razor so I haven't been able to explore much of what I can do in the ViewStart, if I can conditionally set the Layout, or what.
此外,我似乎无法使用 Razor 进行智能感知,所以我无法探索我可以在 ViewStart 中做什么,如果我可以有条件地设置布局,或者什么。
Thoughts?
想法?
回答by Darin Dimitrov
You could set the layout dynamically in your controller action:
您可以在控制器操作中动态设置布局:
public ActionResult Index()
{
var viewModel = ...
return View("Index", "_SomeSpecialLayout", viewModel);
}
回答by SLaks
You can manually set the layout for a view by writing @{ Layout = "~/.../Something.cshtml"; }
on top.
您可以通过@{ Layout = "~/.../Something.cshtml"; }
在顶部书写来手动设置视图的布局。
EDIT: You can pass the layout name as a parameter to the View()
method in the controller.
编辑:您可以将布局名称作为参数传递给View()
控制器中的方法。
回答by Anil Sharma
This method is the simplest way for beginners to control layout rendering in your ASP.NET MVC application. We can identify the controller and render the layouts as per controller. To do this we write our code in the _ViewStart
file in the root directory of the Views folder. The following is an example of how it can be done.
此方法是初学者在 ASP.NET MVC 应用程序中控制布局呈现的最简单方法。我们可以识别控制器并根据控制器渲染布局。为此,我们将代码写入_ViewStart
Views 文件夹根目录下的文件中。以下是如何完成的示例。
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "~/Views/Shared/_Layout.cshtml";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Layout = cLayout;
}
Read complete article I wrote here- "How to Render different Layout in ASP.NET MVC".
阅读我在这里写的完整文章- “如何在 ASP.NET MVC 中呈现不同的布局”。