How To Call Different Layouts Using MVC Application

Create MVC Application

  1. Go to File → New → Project.

    MVC
  1. Choose Web → ASP.NET Web Application (.NET Framework).

    Give the name as you like. I gave the name MobileOrBrowser. Give your project location, followed by clicking OK button. It will open a new Window.

    MVC
  1. Choose MVC, followed by clicking the OK button.

    It will open a new Window, if you want to host your project on Azure. There is a need to fill the required information related to Azure subscription. For now, just click Cancel button.

    MVC
  1. Open Views → Shared→cshtml. By default, this page has a few lines of code.

    MVC

Let’s add another layout.

MVC

We name it _MobileLayout and check the check-box, which is required to be created for a partial view, followed by clicking Add button.

MVC

I copied what was in the _Layout.cshtml by default and pasted it into _MobileLayout.cshtml, thereby making some changes.

In _ViewStart.cshtml, we need to add few lines of code to identify if the site is running on Device mode or the Browser. 

  1. @ {  
  2.     if (!Request.Browser.IsMobileDevice) {  
  3.         Layout = "~/Views/Shared/_Layout.cshtml";  
  4.     } else {  
  5.         Layout = "~/Views/Shared/_MobileLayout.cshtml";  
  6.     }  
  7. }   

For now, we are using default routing, so we need to add few lines of differentiating index view content.

  1. @ {  
  2.     if (!Request.Browser.IsMobileDevice) { < div class = "jumbotron" > < h1 > Browser View < /h1> < p class = "lead" > This is browser view. < /p> < /div>  
  3.     } else { < div class = "jumbotron" > < h1 > Mobile View < /h1> < p class = "lead" > This is mobile view. < /p> < /div>  
  4.     }  
  5. }  

Now, run the Application by clicking F5.

MVC

When you press F12 and refresh you page, then we have model view.

MVC

Next Recommended Reading Layouts And _Viewstart.cshtml In MVC