ASP MVC 3 use different Layouts in different views

2019-01-31 17:20发布

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?

So far I have made a separate Layout.cshtml file for each layout I need.

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.

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.

Thoughts?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-31 17:33

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.

@{
  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".

查看更多
冷血范
3楼-- · 2019-01-31 17:39

You can manually set the layout for a view by writing @{ Layout = "~/.../Something.cshtml"; } on top.

EDIT: You can pass the layout name as a parameter to the View() method in the controller.

查看更多
趁早两清
4楼-- · 2019-01-31 17:43

You could set the layout dynamically in your controller action:

public ActionResult Index()
{
    var viewModel = ...
    return View("Index", "_SomeSpecialLayout", viewModel);
}
查看更多
登录 后发表回答