在Asp.net系统制作过程中,门户类型的网站,我们可以用DIV+CSS+JS+Ajax全部搞定,但是一旦遇到界面元素比较复杂的时候,还是UserControl比较方便一些,各种封装,各种处理,然后拖到主页面,就好了。本文主要讲解如何在UserControl和WebForm页面中利用委托事件传值。本文仅提供一种思路,如果有更好的方案,还敬请赐教。

首先,我们设计一个简单的UserControl页面(实际应用中,我们可以按照业务逻辑,做的复杂一些),请看下图:

Asp.net用户控件和委托事件

然后在Default.aspx页面中,我们只需要显示出从UserControl返回过来的值即可。

在这里,我相信很多人都选择利用Session或者是Application或者是Cache等等,这些确实也都可以,不过我这次利用Delegate 和 Event来实现,好处有几点:首先传过来的值不会莫名其妙的丢失(Session会过期,Cache的东西也会过期,或者是丢失);其次就是代码更好控制,如果UserControl中新加一些其他控件传值过来,不用new session或者是cache等,直接放到事件中,抛向接收页面就行;再者就是由于有事件回调函数,不用再另设Flag来判断UserControl是不是执行完毕等等。

下面是UserControl前台HTML内容,不做讲解:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUC.ascx.cs" Inherits="DelegateWeb.MyUC" %>
<div style="border-bottom:1px solid wheat;width:600px;height:100px; line-height:100px;">
请选择省份:
<asp:DropDownList ID="ddlBind" runat="server" Height="22px"  Width="200px">
<asp:ListItem Value="0">请选择</asp:ListItem>
<asp:ListItem Value="1">上海市</asp:ListItem>
<asp:ListItem Value="2">北京市</asp:ListItem>
<asp:ListItem Value="3">广州市</asp:ListItem>
<asp:ListItem Value="4">深圳市</asp:ListItem>
<asp:ListItem Value="5">河南省</asp:ListItem>
<asp:ListItem Value="6">山东省</asp:ListItem>
</asp:DropDownList>
&nbsp;<asp:TextBox ID="txtKeyWords" runat="server"></asp:TextBox>
&nbsp;<asp:Button ID="btnQuery" runat="server" Text="查询内容"  onclick="btnQuery_Click" />
</div>
View Code

相关文章: