Themes for MVC Bootstrap

I want to enable theme support for bootswatch themes in my MVC 5 application.

I want the user theme to be saved and loaded upon login.

I have expanded my user class to include a theme, and I can successfully install and save the theme on the edit page.

public class User : IdentityUser { public string BootstrapTheme {get;set;} } 

In the BootstrapTheme property, I will save the href attribute for the bootstrap css link. e.g. "~/Content/bootstrap.flatly.min.css"

It is planned to install the theme on the layout page.

<link href="~/Content/bootstrap.spacelab.min.css" rel="stylesheet" />

How can I do this without querying the database every time the page loads?

Being able to do something like <link href="@User.BootstrapTheme" rel="stylesheet" /> would be ideal.

Here is a link on how to save it for one page using localstorage http://wdtz.org/bootswatch-theme-selector.html

+1
twitter-bootstrap asp.net-mvc asp.net-identity owin
Aug 19 '14 at 13:16
source share
1 answer

You should save the topic name / url as a claim against the user, and not as part of the User class:

 await userManager.AddClaimAsync(user.Id, new Claim("MyApp:ThemeUrl", "~/Content/bootstrap.flatly.min.css")); 

When a user logs in, this claim is added to the cookie and you can access it through the extension method:

 public static String GetThemeUrl(this ClaimsPrincipal principal) { var themeClaim = principal.Claims.FirstOrDefault(c => c.Type == "MyApp:ThemeUrl"); if (themeClaim != null) { return themeClaim.Value; } // return default theme url if no claim is set return "path/to/default/theme"; } 

and in your opinion, you will get access to the theme URL as follows:

 <link href="@ClaimsPrincipal.Current.GetThemeUrl()" rel="stylesheet" /> 

Claims about the principle are available in a cookie, therefore, no additional database deletions are required.

Alternatively, you can save the BootstrapTheme user as you already did, but when the user logs in, add this topic as a claim to the id:

 public async Task SignInAsync(IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent) { authenticationManager.SignOut( DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie); var identity = await this.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim("MyApp:ThemeUrl", applicationUser.BootstrapTheme)); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } 

And then access the application in the presentation through the above extension method. I recently wrote a blog post about a similar scenario - you can look there to find out more about how complaints work.

+7
Aug 19 '14 at 13:39 on
source share



All Articles