how to change the themes in asp.net mvc 2

后端 未结 1 756
终归单人心
终归单人心 2021-01-27 17:44

I would like to have an option wherein a user can choose his theme for the site from the dropdown list and the theme applies to that page [atleast].

I want this to be do

1条回答
  •  情歌与酒
    2021-01-27 18:06

    It seems this is not supported out of the box, but here's what I did to implement theming:

    First, I Added the App_Themes folder to my project, and set up a couple of themesenter image description here

    I then decided to try and mimic the Web-forms profile provider as close as possible, and added a profile-property to web.config:

    
      
        
      
    
    

    So, basically what I wanted to do was to be able to load the different css's from the appropriate theme-folder when the theme changed. I did this by implementing a helper method attached to the UrlHelper class so that I could write:

    
    

    This should then load the appropriate themed Site.css, and fall back to ~/Content/Site.css if no file was found.

    The helper is pretty simple:

    public static class UrlHelpers
    {
        public static string Theme(this UrlHelper url, string u)
        {
            if (u.StartsWith("~")) u = u.TrimStart('~');
            SettingsProperty settingsProperty = ProfileBase.Properties["ThemePreference"];
    
            return url.Content("~/App_Themes/"+settingsProperty.DefaultValue + u);
        }
    }
    

    Now, in this version of the code it simply gets the default-value, so you'll need to tweak the code slightly. But as you can see, this is not limited to css-files, but works with everything from .master files to images.

    Update - Using Session instead of profile

    public static class UrlHelpers
    {
        public static string Theme(this UrlHelper url, string u)
        {
            if (u.StartsWith("~")) u = u.TrimStart('~');
    
            object currentThemeName = null;
            if (url.RequestContext.HttpContext.Session != null)
            {
                currentThemeName = url.RequestContext.HttpContext.Session["ThemePreference"];
            }
            return currentThemeName != null ? url.Content(String.Format("~/App_Themes/{0}{1}", currentThemeName, u)) : url.Content("~"+u);
        }
    }
    

    The return-line in this method checks if it found a ThemePreference session-value, and then returnes the appropriate URL for the content requested, otherwise it simply returns the content as it was requested with no App_Theme prefix.

    In your controlleraction for the DropDown postmethod, you'd simply do:

    Session.Add("ThemePreference", whateverValueYouGotFromDropdown);
    

    Update ends

    With some tweaking and fixing, this should do the trick.

    Hope it helps some, even though it's not a complete walkthrough :)

    0 讨论(0)
提交回复
热议问题