asp.net2.0用户控件的应用:站内搜索
站内搜索
对于一些大型的网站,为了方便用户,查询和搜索功能是必不可少的,如果将搜索功能设计成为用户控件,便可以在多个网页中重复使用,从而省去许多重复性的工作。本实例将向读者介绍如何利用用户控件来实现站内查询、搜索功能。实例运行结果如图1和图2所示。
图1 站内搜索用户控件
图2 搜索页传参数
实现过程如下所示。
(1)创建一个Web用户控件menu.ascx,用来实现搜索功能。
(2)创建一个新页SearchInfo.aspx,在该页中添加一个Table表格,用于布局页面。在该Table表格中添加一个已创建好的用户控件menu.ascx,实现查询功能。
(3)主要程序代码。
在Web用户控件menu.ascx上,当用户单击【站内搜索】按钮时,将会触发Button控件的Click事件。将要查询的关键字传递到Search页,代码如下:
protected void cmdSearch_Click(object sender, EventArgs e)
{
Response.Redirect("Search.aspx?str="+this.TextBox1.Text);
}
完整程序代码如下:
★ ★★★★menu.ascx.cs用户控件代码文件完整程序代码★★★★★
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = System.DateTime.Now.ToString("yyyy年MM月dd日") + " " + System.DateTime.Now.DayOfWeek.ToString();
}
protected void cmdSearch_Click(object sender, EventArgs e)
{
Response.Redirect("search.aspx?Str="+this.TextBox1.Text);
}
}
★ ★★★★menu.ascx用户控件设计文件完整程序代码★★★★★
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="menu.ascx.cs" Inherits="WebUserControl" %>
<table style="width: 801px; height: 18px; font-size: 10pt; color: #000099; margin-top: 0px; padding-top: 0px;" class="css" border="0" cellspacing="0">
<tr>
<td align="right" colspan="10" style="background-image: url(image/1.gif); height: 28px">
&nbsp;
&nbsp;&nbsp;
<asp:Label ID="Label1" runat="server" Text="Label" Width="200px" ForeColor="White"></asp:Label>&nbsp;</td>
</tr>
<tr>
<td align="right" colspan="10" style="background-image: url(image/2.gif); color: #ffff66;
height: 7px" class="txt">
输入关键字: &nbsp;
<asp:TextBox ID="TextBox1" runat="server" Width="240px" Height="17px"></asp:TextBox>&nbsp;
<asp:DropDownList ID="DropDownList1" runat="server" Width="78px" CssClass="txt" Height="3px">
<asp:ListItem>时政要闻</asp:ListItem>
<asp:ListItem>环境保护</asp:ListItem>
<asp:ListItem>招商信息</asp:ListItem>
<asp:ListItem>科学教育</asp:ListItem>
<asp:ListItem>法治频道</asp:ListItem>
<asp:ListItem>社会现象</asp:ListItem>
<asp:ListItem>股市信息</asp:ListItem>
<asp:ListItem>时尚娱乐</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="cmdSearch" runat="server" Text="站内搜索" OnClick="cmdSearch_Click" Height="20px" />
&nbsp; &nbsp; &nbsp;</td>
</tr>
<tr>
<td align="center" rowspan="1" style="background-image: url(image/301.gif); width: 151px;">
</td>
<td align="center" style="background-image: url(image/302.gif); width: 72px;">
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/newsList.aspx?id=News" Font-Underline="False" ForeColor="#333333">主页</asp:HyperLink></td>