在ASP.NET中实现MVC模式(三)

** 在 ** ** 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);

}

///

1<summary>
2
3/// Required method for Designer support - do not modify 
4
5/// the contents of this method with the code editor. 
6
7/// </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 函数。

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



Published At
Categories with Web编程
Tagged with
comments powered by Disqus