<form id="webForm" method="post" runat="server"> <asp:DropDownList id="dropDownList" runat="server"></asp:DropDownList> <asp:Button id="button" runat="server" Text="Button"></asp:Button> <asp:DataGrid id="dataGrid" runat="server"></asp:DataGrid> </form>
//页面初始化事件 private void Page_Load(object sender, System.EventArgs e) { if ( ! IsPostBack ) { string SQL_SELECT_PORTAL = "SELECT * FROM PORTAL"; //使用using确保释放数据库连接 //连接字符串存放在Web.Config文件中便于修改 using( SqlConnection conn = new SqlConnection( ConfigurationSettings.AppSettings["ConnectionString"] ) ) { SqlDataAdapter dataAdapter = new SqlDataAdapter( SQL_SELECT_PORTAL, conn ); DataSet dataSet = new DataSet(); dataAdapter.Fill( dataSet ); //设置下拉列表的数据源与文本域、值域 dropDownList.DataSource = dataSet; dropDownList.DataTextField = "portalName"; dropDownList.DataValueField = "portalId"; dropDownList.DataBind(); } } } //Button的Click事件 private void button_Click(object sender, System.EventArgs e) { string SQL_SELECT_SUBJECT = "SELECT * FROM SUBJECT WHERE portalId = {0}"; using( SqlConnection conn = new SqlConnection( ConfigurationSettings.AppSettings["ConnectionString"] ) ) { //用下拉列表选择的值替换掉SQL语句中的待定字符{0} SqlDataAdapter dataAdapter = new SqlDataAdapter( string.Format( SQL_SELECT_SUBJECT, dropDownList.SelectedValue ), conn ); DataSet dataSet = new DataSet(); dataAdapter.Fill( dataSet ); dataGrid.DataSource = dataSet; dataGrid.DataBind(); } }
private static string SQL_SELECT_PORTAL = "SELECT * FROM PORTAL"; private static string SQL_SELECT_SUBJECT = "SELECT * FROM SUBJECT WHERE portalId = {0}"; private static string SQL_CONNECTION_STRING = ConfigurationSettings.AppSettings["ConnectionString"]; public static DataSet GetPortal() { return GetDataSet( SQL_SELECT_PORTAL ); } public static DataSet GetSubject( string portalId ) { return GetDataSet( string.Format( SQL_SELECT_SUBJECT, portalId ) ); } public static DataSet GetDataSet( string sql ) { using( SqlConnection conn = new SqlConnection( SQL_CONNECTION_STRING ) ) { SqlDataAdapter dataAdapter = new SqlDataAdapter( sql, conn ); DataSet dataSet = new DataSet(); dataAdapter.Fill( dataSet ); return dataSet; } } Controller(webForm.aspx.cs):负责转化用户的输入 private void Page_Load(object sender, System.EventArgs e) { if ( ! IsPostBack ) { //调用Model的方法获得数据源 dropDownList.DataSource = SQLHelper.GetPortal(); dropDownList.DataTextField = "portalName"; dropDownList.DataValueField = "portalId"; dropDownList.DataBind(); } } private void button_Click(object sender, System.EventArgs e) { dataGrid.DataSource = SQLHelper.GetSubject( dropDownList.SelectedValue ); dataGrid.DataBind(); }
Page Controller(BasePage.cs): public class BasePage : System.Web.UI.Page { private string _title; public string Title//页面标题,由子类负责指定 { get { return _title; } set { _title = value; } } public DataSet GetPortalDataSource() { return SQLHelper.GetPortal(); } public DataSet GetSubjectDataSource( string portalId ) { return SQLHelper.GetSubject( portalId ); } protected override void Render( HtmlTextWriter writer ) { writer.Write( "<html><head><title>" + Title + "</title></head><body>" );//统一的页面头 base.Render( writer );//子页面的输出 writer.Write( @"<a href=""http://www.asp.net"">ASP.NET</a></body></html>" );//统一的页面尾 } }
public class webForm : BasePage//继承页面基类 { private void Page_Load(object sender, System.EventArgs e) { Title = "Hello, World!";//指定页面标题 if ( ! IsPostBack ) { dropDownList.DataSource = GetPortalDataSource();//调用基类的方法 dropDownList.DataTextField = "portalName"; dropDownList.DataValueField = "portalId"; dropDownList.DataBind(); } } private void button_Click(object sender, System.EventArgs e) { dataGrid.DataSource = GetSubjectDataSource( dropDownList.SelectedValue ); dataGrid.DataBind(); } }
因为Front Controller模式要比上面两个模式复杂一些,我们再来看看例子的类图:
<!-- 指定对Dummy开头的aspx文件交由Handler处理 --> <httpHandlers> <add verb="*" path="/WebPatterns/FrontController/Dummy*.aspx" type="WebPatterns.FrontController.Handler,WebPatterns"/> </httpHandlers> <!-- 指定名为FrontControllerMap的页面映射块,交由UrlMap类处理,程序将根据key找到对应的url作为最终的执行路径,您在这可以定义多个key与url的键值对 --> <configSections> <section name="FrontControllerMap" type="WebPatterns.FrontController.UrlMap, WebPatterns"></section> </configSections> <FrontControllerMap> <entries> <entry key="/WebPatterns/FrontController/DummyWebForm.aspx" url="/WebPatterns/FrontController/ActWebForm.aspx" /> 。。。 </entries> </FrontControllerMap> 修改webForm.aspx.cs: private void button_Click( object sender, System.EventArgs e ) { Response.Redirect( "DummyWebForm.aspx?requestParm=" + dropDownList.SelectedValue ); } 当程序执行到这里时将会根据Web.Config里的定义触发类Handler的ProcessRequest事件: Handler.cs: public class Handler : IHttpHandler { public void ProcessRequest( HttpContext context ) { Command command = CommandFactory.Make( context.Request.Params ); command.Execute( context ); } public bool IsReusable { get { return true; } } }
public class CommandFactory { public static Command Make( NameValueCollection parms ) { string requestParm = parms["requestParm"]; Command command = null; //根据输入参数得到不同的Command对象 switch ( requestParm ) { case "1" : command = new FirstPortal(); break; case "2" : command = new SecondPortal(); break; default : command = new FirstPortal(); break; } return command; } } public interface Command { void Execute( HttpContext context ); } public abstract class RedirectCommand : Command { //获得Web.Config中定义的key和url键值对,UrlMap类详见下载包中的代码 private UrlMap map = UrlMap.SoleInstance; protected abstract void OnExecute( HttpContext context ); public void Execute( HttpContext context ) { OnExecute( context ); //根据key和url键值对提交到具体处理的页面 string url = String.Format( "{0}?{1}", map.Map[ context.Request.Url.AbsolutePath ], context.Request.Url.Query ); context.Server.Transfer( url ); } } public class FirstPortal : RedirectCommand { protected override void OnExecute( HttpContext context ) { //在输入参数中加入项portalId以便页面处理 context.Items["portalId"] = "1"; } } public class SecondPortal : RedirectCommand { protected override void OnExecute(HttpContext context) { context.Items["portalId"] = "2"; } } 最后在ActWebForm.aspx.cs中: dataGrid.DataSource = GetSubjectDataSource( HttpContext.Current.Items["portalId"].ToString() ); dataGrid.DataBind();
<%@ OutputCache Duration="60" VaryByParam="none" %>,
public static DataSet GetPortal() { DataSet dataSet; if ( HttpContext.Current.Cache["SELECT_PORTAL_CACHE"] != null ) { //如果数据存在于缓存中则直接取出 dataSet = ( DataSet ) HttpContext.Current.Cache["SELECT_PORTAL_CACHE"]; } else { //否则从数据库中取出并插入到缓存中,设定绝对过期时间为3分钟 dataSet = GetDataSet( SQL_SELECT_PORTAL ); HttpContext.Current.Cache.Insert( "SELECT_PORTAL_CACHE", dataSet, null, DateTime.Now.AddMinutes( 3 ), TimeSpan.Zero ); } return dataSet; }