代码改变世界

Asp.net 基础8(自定义控件之缓存)

2010-05-14 10:54  c#在路上  阅读(688)  评论(0)    收藏  举报
1,
简单页面缓存,设置缓存的时间,缓存的机制

Duration 
页或用户控件进行缓存的时间(以秒计)。在页或用户控件上设置该属性为来自对象的 HTTP 响应建立了一个过期策略,并将自动缓存页或用户控件输出。
注意这是必选属性。如果未包含该属性,将出现分析器错误。
VaryByParam 
分号分隔的字符串列表,用于使输出缓存发生变化。
默认情况下,这些字符串与随 GET 方法属性发送的查询字符串值对应,或与使用 POST 方法发送的参数对应。
将该属性设置为多个参数时,对于每个指定参数组合,输出缓存都包含一个不同版本的请求文档。
可能的值包括 none、星号 (*) 以及任何有效的查询字符串或 POST 参数名称。
警告:在 ASP.NET 页和用户控件上使用 @ OutputCache 指令时,需要该属性或 VaryByControl 属性。
 如果不希望通过指定参数来改变缓存内容,请将值设置为 none。如果希望通过所有的参数值改变输出缓存,请将属性设置为星号 (*))。

<%@ OutputCache Duration="3600" VaryByParam="none"%>

2,缓存用户自定义控件
在自定义用户控件时,是用outputcache指令

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OutCacheUserControl.ascx.cs" Inherits="TestCodeBehind.OutCacheUserControl" %>
<%@ OutputCache Duration="3600" VaryByParam="none" %>
<asp:Label ID="lbl1" runat="server" Text="用户控件刷新时间:"></asp:Label>
<br />
<asp:Label ID="lblTime" runat="server" Text=""></asp:Label>

 3,缓存数据

通过编程方式来缓存数据,

代码

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Model;
using BussinessIntegrateLayer;
using System.Collections.Generic;

namespace TestCodeBehind
{
    
public partial class OutCacheDataSourceForm : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
            DataView couseView 
= (DataView)Cache["CouseCache"];
            
if (couseView == null)
            {
                CourseService service 
= new CourseService();
                DataSet couseDataSet 
= service.GetAllList();
                DataView tableView 
= couseDataSet.Tables[0].DefaultView;
                couseView 
= tableView;
                Cache[
"CouseCache"= tableView;
            }
            
else
                Response.Output.WriteLine(
"<h2>Load from cache</h2>");
            
this.listCourse.DataSource = couseView;
            
this.listCourse.DataBind();
        }
    }
}

 

 

代码
客户端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OutCacheDataSourceForm.aspx.cs" Inherits="TestCodeBehind.OutCacheDataSourceForm" %>

<!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:ListBox ID="listCourse" runat="server" DataTextField="Title" 
            DataValueField
="Credits"></asp:ListBox>
    
</div>
    
</form>
</body>
</html>