I have a set of stylesheets with different colour options. I have created a user control with a list of the stylesheet options which are setup as linkbuttons. On click I set a session variable with the path of the stylesheet I want to use, then on the master page I check this session and set the stylesheet accordingly.
The problem is that the stylesheet changes don’t take effect until I refresh the page again. How can I force the stylesheet to reload instantly?
Here is my usercontrol:
<ul id="swatch">
<li>
<div class="green"></div>
<asp:LinkButton ID="lbGreen" runat="server" Text="Green" ClientIDMode="Static"
onclick="lbGreen_Click"></asp:LinkButton>
</li>
<li>
<div class="maroon"></div>
<asp:LinkButton ID="lbMaroon" runat="server" Text="Maroon" ClientIDMode="Static"
onclick="lbMaroon_Click"></asp:LinkButton>
</li>
<li>
<div class="silver"></div>
<asp:LinkButton ID="lbSilver" runat="server" Text="Silver" ClientIDMode="Static"
onclick="lbSilver_Click"></asp:LinkButton>
</li>
<li>
<div class="black"></div>
<asp:LinkButton ID="lbBlack" runat="server" Text="Black" ClientIDMode="Static"
onclick="lbBlack_Click"></asp:LinkButton>
</li>
</ul>
Here is the code behind for this control:
public partial class StylesheetPicker : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lbGreen_Click(object sender, EventArgs e)
{
SetStylesheet("green");
}
protected void lbMaroon_Click(object sender, EventArgs e)
{
SetStylesheet("maroon");
}
protected void lbSilver_Click(object sender, EventArgs e)
{
SetStylesheet("silver");
}
protected void lbBlack_Click(object sender, EventArgs e)
{
SetStylesheet("black");
}
private void SetStylesheet(string selectedStyle)
{
switch (selectedStyle)
{
case "green":
Session["style"] = "/css/green.css";
break;
case "maroon":
Session["style"] = "/css/maroon.css";
break;
case "silver":
Session["style"] = "/css/silver.css";
break;
case "black":
Session["style"] = "/css/black.css";
break;
default:
Session["style"] = "/css/green.css";
break;
}
}
}
and then here is the code snippet I have on my master page:
if(Session["style"] != null)
{
var stylesheet = Session["style"];
<link rel="stylesheet" type="text/css" href="@stylesheet" />
}
else
{
<link rel="stylesheet" type="text/css" href="/css/green.css" />
}
It seems I have to click the linkbuttons twice to get the stylesheet to change. How can I do it so when the button is clicked it changes instantly?
Thanks
Give your stylesheet link element an id, then you should be able to change the href on it to something else. This code works in chrome, not sure about other browsers:
Javascript to change it:
For the server side problem you could problem just redirect after they postback a change to it to get it to take effect on the next page load.