(收藏)在ASP.NET中实现Model-View-Controller模式,三

模型及控制器部分:

这个解决方案的第二个部分是被隐藏的后台代码:

using System;

using System.Data;

using System.Data.SqlClient;

public class Solution : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button submit;

protected System.Web.UI.WebControls.DataGrid MyDataGrid;

protected System.Web.UI.WebControls.DropDownList recordingSelect;

private void Page_Load(object sender, System.EventArgs e)

{

if(!IsPostBack)

{

String selectCmd = "select * from Recording";

SqlConnection myConnection =

new SqlConnection(

"server=(local);database=recordings;Trusted_Connection=yes");

SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);

DataSet ds = new DataSet();

myCommand.Fill(ds, "Recording");

recordingSelect.DataSource = ds;

recordingSelect.DataTextField = "title";

recordingSelect.DataValueField = "id";

recordingSelect.DataBind();

}

}

void SubmitBtn_Click(Object sender, EventArgs e)

{

String selectCmd =

String.Format(

"select * from Track where recordingId = {0} order by id",

(string)recordingSelect.SelectedItem.Value);

SqlConnection myConnection =

new SqlConnection(

"server=(local);database=recordings;Trusted_Connection=yes");

SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);

DataSet ds = new DataSet();

myCommand.Fill(ds, "Track");

MyDataGrid.DataSource = ds;

MyDataGrid.DataBind();

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.submit.Click += new System.EventHandler(this.SubmitBtn_Click);

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

}

这里将代码从上个实现方法单独的文件移动到了一个它自己的文件中。并通过一些机制把视图以及模型控制器这两个部分连接成一个整体,如这个类中的成员变量与Solution.aspx文件中所用的控件是同名的。另外一个必须显示指出的是控制器如何将行为与其所对应的事件进行连接。在这个例子中InitializeComponent函数连接了两个事件。第一个将Load事件与 Page_Load函数连接,第二个是Click事件,当Submit按钮被点击时调用SubmitBtn_Click函数。

代码分离是一种将视图部分与模型及控制器部分相分离的一种优秀的机制。但当你想把分离出的后台的代码给其它页面重用时可能还是不足的。在技术上,将页面背后的代码复用是可行的,但随着你需要共享的页面的增加,把页面与后台代码相连接是很困难的。