您可以使用带有 Razor 语法的服务器端代码或纯 JavaScript 来实现您的场景。为 cookie 混合 JavaScript 和服务器端代码有时会产生意想不到的结果,因此请选择纯服务器端方法或纯 JavaScript 方法。
我的示例中的二进制 cookie 称为 bodyStyle,它的值为 1 或 0。我正在创建一个持久性 cookie,该 cookie 将从今天起 30 天到期,并且将在您域中的页面上可用/持久。此外,您可以在创建 cookie 时添加一些条件检查或根据您的要求在两种方法中设置其值。
我使用 cookie 值添加到正文的自定义类是 miniNavBar。
服务器端方法
body 标签通常会出现在共享视图中,因此将下面的 Razor 代码添加到共享视图中。
使用二进制 cookie 动态设置正文类的 C# Razor 代码
@{
//set bodyStyle cookie based on some condition using a if statement as per your requirements
Response.Cookies["bodyStyle"].Value = "1";
Response.Cookies["bodyStyle"].Expires = DateTime.Now.AddMinutes(2);
}
<body class="@(Response.Cookies["bodyStyle"].Value == "1" ? "miniNavBar" : "")">
JavaScript 方法
下面的代码可以进入任何需要这个逻辑的视图,或者如果你想将它应用到所有视图,可以将它添加到共享布局视图中。
使用二进制 cookie 动态设置 body 类的 JavaScript 代码
<script type="text/javascript">
//main cookie function that will contain your logic for creating the binary cookie
function setBodyCookie() {
//if perisistent cookie exists then do not create it
if (document.cookie.indexOf("bodyStyle=0") >= 0 || document.cookie.indexOf("bodyStyle=1") >= 0) {
return;
}
//create body cookie if it does not exist
//you can add an if statement here when creating a cookie based on your scenario
var now = new Date();
now.setTime(now.getTime() + 30 * 24 * 60 * 60 * 1000);//expire this in 30 days from now
document.cookie = "bodyStyle=1;expires=" + now.toUTCString() + ";path=/";
}
$(document).ready(function () {
//set binary cookie according to your requirements
setBodyCookie();
//add class to body if binary cookie has a value of 1
if (document.cookie.indexOf("bodyStyle=1") >= 0) {
$("body").addClass("miniNavBar");
}
});
</script>
如果您想避免闪烁,另一种 JavaScript 解决方案可能是将文档就绪事件代码放在标记中的正文标记之后,并删除您正在使用的原始文档就绪事件,如下所示。您会注意到准备好的文档没有在下面的代码中使用。
<body class="expandedNavBar">
<script>
//set binary cookie according to your requirements
setBodyCookie();
//add class to body if binary cookie has a value of 1
if (document.cookie.indexOf("bodyStyle=1") >= 0) {
//remove all classes that are already there or just remove the
//the ones you like to
$("body").removeClass();
//add your class now
$("body").addClass("miniNavBar");
}
</script>
另一个替代方法是您可以使用.hide 类来避免闪烁,因为在文档就绪事件中更改了正文类。这显示在下面的示例代码中。
<style>
.hide{ visibility:hidden}
</style>
<script>
$(document).ready(function () {
//set binary cookie according to your requirements
setBodyCookie();
//add class to body if binary cookie has a value of 1
if (document.cookie.indexOf("bodyStyle=1") >= 0) {
$("body").removeClass("hide");//remove the hide class
$("body").addClass("miniNavBar");
}
});
</script>
<body class="hide">