天天看點

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

   }

   /// <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函數。

代碼分離是一種将視圖部分與模型及控制器部分相分離的一種優秀的機制。但當你想把分離出的背景的代碼給其它頁面重用時可能還是不足的。在技術上,将頁面背後的代碼複用是可行的,但随着你需要共享的頁面的增加,把頁面與背景代碼相連接配接是很困難的。