Changing MVC Styles
- This page will show you how to dynamically change between two master pages to change the style of your website.
For this example, i will hopping between The normal MVC ASPX framework and a Bootstrap framework.
Setting up your Master Pages
- Start off by creating a second master page in your project, as well as creating an aspx file that will be used to do the swap between Master pages.
For this example my aspx page will be titled "SwitchSkin.aspx".
- Open up tyour new aspx file and add the following c# script to the top of your page. This will be the code that causes the swap between Master pages.
This method will use cookies to keep track of witch Master should be currently active.
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie myCookie = Request.Cookies["masterCookie"];
if (myCookie == null)
{
myCookie = new HttpCookie("masterCookie", "[keyword for master 1]");
}
else if (myCookie.Value == "[keyword for master 2]")
{
myCookie.Value = "[keyword for master 1]";
}
else
{
myCookie.Value = "[keyword for master 2]";
}
Response.Cookies.Add(myCookie);
Response.Redirect("/");
} </script>
Setting up the Switch
-
Next, go to the page that you want to contain the button to inititate the switch between Master pages.
-
Add an HTML action set to go to your new aspx page.
i.e <%: Html.ActionLink("Switch Skin", "SwitchSkin", "Home") %>
-
When the user clicks on this link, it will go to your aspx page and run the code to change the master.
Keeping the Master Swap
-
Now that you have your site swapping master pages. We need to make sure each page recognizes the swap.
To do this, go to each of your sites controllers. Inside each one add the following code:
public ActionResult MasterView()
{
var myView = View();
HttpCookie myCookie = Request.Cookies["masterCook"];
if (myCookie == null)
{
myCookie = new HttpCookie("masterCook", "[keyword for master 1]");
Response.Cookies.Add(myCookie);
}
else if (myCookie.Value == "bootstrap")
{
myView.MasterName = "~/Views/Shared/SiteBootstrap.Master";
}
else
{
myView.MasterName = "~/Views/Shared/Site.Master";
}
return myView;
} -
Change all of the other ActionResult methods in each of the controllers to return the results of MasterView(). For example:
public ActionResult AnotherPage()
{
ViewBag.Message = "Another Page.";
return MasterView();
}
- You now can change back and forth between Master pages, and therefore, styles!