Monday, February 17, 2014

Different ways of rendering layouts in Asp.Net MVC

In this article, I am going to expose the different ways to apply layout pages for your application. Suppose we have to render the layouts as shown in the fig. by using various ways.

Method 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
We can change the default rendering of layouts with in _ViewStart file by using the below code:

1.  @{
2.   var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
3.   
4.   string layout = "";
5.   if (controller == "Admin")
6.   {
7.   layout = "~/Views/Shared/_AdminLayout.cshtml";
8.   }
9.   else
10. {
11. layout = "~/Views/Shared/_Layout.cshtml";
12. }
13.
14. Layout = layout;
15.}
Method 2 : Return Layout from ActionResult
We can also override the default layout rendering by returning the layout from the ActionResult by using the below code:

1.  public ActionResult Index()
2.  {
3.   RegisterModel model = new RegisterModel();
4.   //TO DO:
5.   return View("Index", "_AdminLayout", model);
6.  }
Method 3 : Define Layout with in each view on the top
We can also override the default layout rendering by defining the layout on the view by using the below code:
1.  @{
2.   Layout = "~/Views/Shared/_AdminLayout.cshtml";
3.  }

No comments:

Post a Comment

Generate All Database Backup From Sql Server Using Query

DECLARE   @name   VARCHAR ( 50 )   -- database name DECLARE   @path   VARCHAR ( 256 )   -- path for backup files DECLARE   @fileName  ...