视图
<link type="text/css" rel="stylesheet" href="@Url.Action("Css")" />
<h2>Theme主题切换</h2>
@using (Html.BeginForm())
{
string theme = ViewBag.Theme.ToString();
@Html.RadioButton("theme", "Default", theme == "Default");
<span>默认主题1(宋体)</span>
<br />
@Html.RadioButton("theme", "Theme1", theme == "Theme1");
<span>默认主题2(黑体)</span>
<br />
@Html.RadioButton("theme", "Theme2", theme == "Theme2");
<span>默认主题3(楷体)</span>
<br />
<input type="submit" value="保存" />
}
控制器
public ActionResult Theme()
{
//预定一个Cookie,如果网页本身有Cookie就获取原来的,没有的话就新建一个Cookie
HttpCookie cookie = Request.Cookies["theme"] ?? new HttpCookie("theme", "Default");
ViewBag.Theme = cookie.Value;//利用ViewBag保存Cookie值,并传到视图页面中
return View();
}
/// <summary>
/// 讲当前的主题样式保存到Cookie中
/// </summary>
/// <param name="theme"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Theme(string theme)
{
HttpCookie cookie = new HttpCookie("theme", theme);
cookie.Expires = DateTime.MaxValue;//设置时间
Response.SetCookie(cookie); //更新cookie
ViewBag.Theme = cookie.Value;
return View();
}
/// <summary>
/// 通过主题切换样式
/// </summary>
/// <returns></returns>
public ActionResult Css()
{
HttpCookie cookie = Request.Cookies["theme"] ?? new HttpCookie("theme", "Default");
switch (cookie.Value)
{
case "Theme1":
return Content("body{font-family:1.2em;font-family:SimHei;background-color:green;}", "text/css");
case "Theme2":
return Content("body{font-family:1.2em;font-family:KaiTi;background-color:yellow;}", "text/css");
default: return Content("body{font-family:1.2em;font-family:SimSong;background-color:red;}", "text/css");
}
}