EqEdi
EqEdi

Reputation: 61

How to change theme dynamically in mvc3

I want to change the theme of my web page on user selection I am using MVC3. My idea is to include various style sheets inside the Content folder and let the _layout.cshtml file decide which css file to call on user selection At present all i can do is include a single tag which is reflected on all the pages I want the view to be the same but the style sheets should change on selection.

I tried this code inside _Layout.cshtml:

    <script type="text/javascript">
    function loadjscssfile(filename) {
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)   

Inside Body tag:

<select>
        <option onclick="loadjscssfile("@Url.Content("~/Content/Site1.css")")">Theme1</option>
        <option onclick="loadjscssfile("@Url.Content("~/Content/Site2.css")")">Theme2</option>
        </select>  

But this also does not work:( Please help me.I am new to MVC3...

Upvotes: 0

Views: 1855

Answers (2)

Iridio
Iridio

Reputation: 9271

This post should help you:

ASP.NET MVC Theme Supported Razor View Engine

UPDATE: This sample won't compile with mvc3. You should do some "find and replace" for

ViewModel.Title -> ViewBag.Title
ViewModel.Message -> ViewBag.Message
ViewModel.PasswordLength -> ViewBag.PasswordLength

return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this, incompletMatch); -> return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);

Upvotes: 1

Charlie Pops
Charlie Pops

Reputation: 78

I think it is better if you keep one stylesheet and only changes a class on your body tag

<body class="red|blue">
    //your content
</body>

and inside your style sheet you only add different styles to each selector

.red{
    background-color: red;
}

.blue{
    background-color: blue;
}

Upvotes: 0

Related Questions