您的位置:首页 > 编程语言 > ASP

asp.net之cookie(设置css)

2015-10-26 18:17 483 查看
cookie是asp.net中跨页面传值的方法之一,通过cookie可以对页面的css进行设置。

以下是一个例程:

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="Lab_css" runat="server" Text="Label" CssClass="" ></asp:Label>
<br />
<br />
<asp:DropDownList ID="lab_color" runat="server">
<asp:ListItem Value="blue">blue</asp:ListItem>
<asp:ListItem Value="green">green</asp:ListItem>
<asp:ListItem Value="red">red</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="lab_fontsize" runat="server">
<asp:ListItem Value="3px">3px</asp:ListItem>
<asp:ListItem Value="2em">2em</asp:ListItem>
<asp:ListItem Value="1em">1em</asp:ListItem>
</asp:DropDownList>

<br />

</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>


Default.aspx.css
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HttpCookie _hk = Request.Cookies["testCss"];
if (_hk != null)
{
string _color = _hk.Values[<span style="color:#ff0000;">"color"</span>];// 注意与button1_click事件中的cookie子键名对应,切记
string _fontsize = _hk.Values["fs"];

Lab_css.Style.Add("color", _color);
Lab_css.Style.Add("font-size", _fontsize);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string _color, _fs;
_color = lab_color.SelectedValue;
_fs = lab_fontsize.SelectedValue;

HttpCookie _hk = new HttpCookie("testCss");
_hk.Values.Add("color", _color);
_hk.Values.Add("fs", _fs);
_hk.Expires = DateTime.MaxValue;
Response.Cookies.Add(_hk);
//   Response.Write(lab_color.SelectedValue);
Lab_css.Style.Add("color", _color);
Lab_css.Style.Add("font-size", _fs);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: