views:

11

answers:

1

I am rather new to MVC applications, and one thing I am trying to accomplish is enabling or disabling stylesheets based on a Session value.

I have stylesheets referenced in my Site.Master page in this manner:

<%=Html.Stylesheet("~/styles/main.css", "string")%> <%=Html.Stylesheet("~/styles/additions.css", "string")%>

Right now, for testing, I have been putting an if statement around the Html.Stylesheet tags saying:

<% if (Session["cssRule"] = "enableCss") { %>

<%=Html.Stylesheet("~/styles/main.css", "screen")%> <%=Html.Stylesheet("~/styles/additions.css", "screen")%>

<%} %>

So if the 'cssRule' Session value is null, no CSS loads. Currently this is working fine, but it is not exactly what I am looking for. Right now I set the Session value in the Controller when the user logs in, but ultimately I need to set the value of the Session variable depending on if a user clicks the enable or disable button. Since I have been primarily using webforms for the past year and a half, I just want to drop a hyperlink and set an event for it, but alas, this is the future of MVC so I need to figure out how I can do something like this..

So my real question is how can I set the Session of the "cssRule" value by clicking a link using MVC?

A: 

I'll assume you want to use a standard link (not ajax) and that your main view is Index

Just add a method in your controller (pseudocode)

public ActionResult ToggleCSS()
{
    if (Session["cssRule"] != null && Session["cssRule"] == "enableCSS") 
    {
          Session["cssRule"] = "disableCSS";
    }
    else
    {
          Session["cssRule"] = "enableCSS";
    }
    return View("Index");
}

Then in your view, use

<%= Html.ActionLink("ToggleCSS", "ControllerName") %>

You can use lots of fancy different methods to obtain the same result; use ajax and relaod the page, or not, or redirect to a page listing css files to apply, etc... but this one should work :)

samy