MVC视图界面的主题定制

视图

<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");
            }

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值