MVC: Set Master Page File based on day and Night time

  
Here you need to follow just simple four steps to get this activity done.

Step1:

On your Controller set a “TempData” [a variable which is shared among controller and view internally using session] variable like below to identify current time is Day or Night.

     
   public ActionResult Index()
   {

      TimeSpan time = DateTime.Now.TimeOfDay;
      if ((time > new TimeSpan(05, 59, 00)) && (time < new TimeSpan(17, 59, 00)))
            {
                TempData["DayNight"] = true; //True is Day

            }
            else
            {
                TempData["DayNight"] = false; //False in Night
           
            }
     return View();
    }



I have added it on “Index” Action method on some controller. It is not mandatory to set it on only index, you can use any other action method but need to make sure that you once after executing action method you should return any view basically where[returning View] we will do our stuff for Master page file selection.

Step2:

Create your view by right clicking on Action method à Add View. Default name is Index. Press okay. So a new View called “Index” gets created on the view folder.

[This is step is pretty much common in MVC. We create controller named as Employee, on the Employee controller we have an action method named as Index, then we right click and add a view. On the View folder you have a subfolder Employee and within that one page “Index.aspx” (aspx engine) or “Index.cshtml”(for razor engine)]


Step3:

Now  add two views in your shared folder like below. They are named as “_DayLayout” and “_NightLayout”. Simple and straight forward.



Step4:

Now top of your main view [The View which you have created in Step2] include the below. I am using MVC3 with Razor view.


@{ 
    if (Convert.ToBoolean(@TempData["DayNight"]) == true)
    {
        Layout = "~/Views/Shared/_DayLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_NightLayout.cshtml";
    }   
}



You are done. Execute and Check it where as in ASP.Net we use to set up master page file in “Page_PreInit()  method . Feel free to post your query @nit.pradip@gmail.com


1 comment:

  1. Pretty section of content. I just stumbled upon your website and in accession
    capital to assert that I get in fact loved account your blog posts.
    Any way I will be subscribing on your augment and even I success you get right of entry to consistently rapidly.


    Also visit my webpage :: winter abby ale

    ReplyDelete