解释
我想通过partalview内的按钮切换bootstrap 5.3主题颜色。
切换按钮是根据我的具体需求定制的,值保存在 cookie 中,我在需要时调用它。
部分视图将包含在导航栏菜单中。
出于某种奇怪的原因,对于这种情况,我无法找到合适的解决方案。
问题
如何实现,哪个是正确的方法?
部分视图代码
@{
static void ToggleTheme()
{
string bg = HttpContext.Request?.Cookies["mybg"]?.ToString();
if (bg == "light" || bg == null)
{
HttpContext.Response.Cookies.Delete("mybg");
HttpContext.Response.Cookies.Append("mybg", "dark");
}
else
{
HttpContext.Response.Cookies.Delete("mybg");
HttpContext.Response.Cookies.Append("mybg", "light");
}
}
}
<button type="submit" name="submit" class="btn btn-sm btn-outline-light" onclick="ToggleTheme()">
主题
您可以遵循的简单演示:
部分视图(位于
Pages/Shared
或Views/Shared
文件夹中)
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
// Read the current theme preference from the cookie
string currentTheme = HttpContextAccessor.HttpContext.Request?.Cookies["mybg"]?.ToString();
}
<button type="submit" name="submit" class="btn btn-sm btn-outline-light" onclick="ToggleTheme()">ChangeTheme</button>
<script>
// Function to toggle the theme and save preference in a cookie
function ToggleTheme() {
var currentTheme = document.body.classList.contains('theme-dark') ? 'light' : 'dark';
// Toggle theme class on the body element
document.body.classList.toggle('theme-dark');
// Save the theme preference in a cookie
document.cookie = "mybg=" + currentTheme + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}
// Set initial theme based on the cookie
window.onload = function () {
var currentTheme = "@currentTheme";
if (currentTheme === "dark") {
document.body.classList.add('theme-dark');
}
};
</script>
<style>
.theme-dark {
background-color: #1f1f1f; /* Dark background color */
color: #ffffff; /* Light text color on dark background */
/* Additional styles for dark theme elements */
}
</style>
布局
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">IdentityProj8</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
<partial name="_Partial" />
</div>
</div>
</nav>