Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change layout in controller depending on url

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

I want to get result with different Layout on request "/External/View".

How can i achieve this?

like image 712
Nikita Martyanov Avatar asked Mar 21 '12 07:03

Nikita Martyanov


People also ask

What is the controller in URL pattern?

Typical URL Patterns in MVC Applications The MvcHandler HTTP handler determines which controller to invoke by adding the suffix "Controller" to the controller value in the URL to determine the type name of the controller which will handle the request. The Action value in the URL determines, which Action method to call.

How do you give a controller a URL?

If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.


1 Answers

Although you can override the layout from the controller as has been suggested in another answer, in my opinion this means the controllers are getting just too involved in determining what the UI will be. Best to leave this purely to the Views to decide.

The closest to what you're asking is to do this in your 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 alternative layout.

Might want to check the leading "/" is correct on there, I can't remember if it is.

If you put this in the existing _ViewStart, then any view that is being rendering in response to a url starting with "/External" will use this new layout, otherwise the 'normal' one will be used.

Another approach is to use the routing table to add a route value that can be used here to make a layout decision; but I've gone for this approach to keep it simple.

like image 136
Andras Zoltan Avatar answered Oct 07 '22 16:10

Andras Zoltan