Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How can we use different layout for a different browser in asp.net MVC?

user-image
Question added by Javed Ahmad , Senior Developer , HCL Technologies Ltd
Date Posted: 2017/08/03
Pooja Trivedi
by Pooja Trivedi , Scrum Master , Emirates Airlines

.Net provides System.Web.HttpBrowserCapabilities namespace to check the browser name, type and other properties 

In your ViewStart.cshtml, check for the following

@{

    if(Request.Browser.Browser== "IE")

      {

           Layout="~/Views/Shared/_Layout1.cshtml"

 else {  

        Layout = "~/Views/Shared/_Layout2.cshtml";  

    }  

Abdul Ghani
by Abdul Ghani , Senior Design Engineer , Fatin Home Furniture LLC

t is very important to understand rendering Layouts in ASP.NET MVC. To understand Layouts Asp.Net MVC, we can consider Layouts are like as Master Pages in Asp.Net Web Forms. That’s why, as Master Pages allow us to maintain consistent look and feel across the ASP.NET Web Forms, Layouts are also help us to maintain consistent look and feel across all the views within your Asp.Net MVC application. Like Master Pages, Layout may contain common CSS, jQuery files across the multiple Views and one or more placeholders for which Views provide content.

Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{  var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();   string cLayout = "";  if (controller == "Webmaster") {  cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";  }  else {  cLayout = "~/Views/Shared/_Layout.cshtml";  }  Layout = cLayout; Procedure 2 : Set Layout by Returning from ActionResult

One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.

1 2 3 4 5 6 public ActionResult Index() {  SampleModel model = new SampleModel();  //Any Logic  return View("Index", "_WebmasterLayout", model); } Procedure 3 : View - wise Layout (By defining Layout within each view on the top)

ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.

1 2 3 @{  Layout = "~/Views/Shared/_WebmasterLayout.cshtml"; }

More Questions Like This