Change layout in controller based on url

I have a PlayerController controller and actions inside: View , Info , List . So, on urls "/ Player / View" I get the result with the default layout.

I want to get the result with a different layout for the query "/ External / View".

How can i achieve this?

+6
source share
2 answers

Although you can redefine the layout from the controller, as suggested in another answer, in my opinion, this means that the controllers are too involved in determining what the user interface will be. It is best to leave it pure in views to decide.

The closest thing to what you are asking is to do this in the current "~/Views/_ViewStart.cshtml" :

 @{ if(Context.Request.Path.StartsWith("/External", StringComparison.OrdinalIgnoreCase)) Layout = "~/Views/_ExternalLayout.cshtml"; else Layout = "~/Views/_Layout.cshtml"; } 

Where "~/Views/_ExternalLayout.cshtml" is your alternate layout.

It may be worth checking that the lead "/" correct, I can’t remember if it is.

If you put this in an existing _ViewStart, then any view that is executed in response to a URL starting with "/External" will use this new layout, otherwise normal will be used.

Another approach is to use a routing table to add a route value that can be used here to make a layout decision; but I went for this approach to make things simple.

+13
source

You can specify which layout to use when returning the view within the action of the ExternalController controller.

 return View("View", "~/Views/Shared/_AnotherLayout.cshtml") 
+8
source

Source: https://habr.com/ru/post/911273/


All Articles