Marlon Fernando
Marlon Fernando

Reputation: 29

ASP.Net MVC 4 Load css File dynamically

I have a website on which there is a need for customization, which means i need to change the theme of the page depending on the option selected by the user. I need to know how to change the css file which is rendered through Layout.cshtml according to the users selection.

These are the two css file in my layout.cshtml

@Styles.Render("~/Content/style1.css") -> Theme 1 @Styles.Render("~/Content/style2.css") -> Theme 2

I have assign two links to click in order to change the css file in my home webpage(Link 1-Theme 1,Link 2- Theme 2) but i don't know how to change it.

My initial idea was to have two links and when the link is pressed it will be sent to a controller from which it will be redirected to the page after selecting the appropriate css file from layout.cshtml depending on the users selection using an if condition, i guess that idea is not possible.

Please let me know the best way to do this since i need to implement this solution in my website soon.

Upvotes: 0

Views: 5067

Answers (1)

G. Stoynev
G. Stoynev

Reputation: 7783

You could have a query string parameter that sets whichStyleFlavor:

@{
    string whichStyleFlavor = "1";
    ... some logic to check what they requested and change whichStyleFlavor
}

@Styles.Render("~/Content/style" + whichStyleFlavor + ".css")

Or you can do it on the client, by switching the CSS tag.

From here:

<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script type="text/javascript">
function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
}

Upvotes: 1

Related Questions