天天看點

在ASP.NET中實作MVC模式(四)

ASP.NET 中實作 Model-View-Controller 模式(四) 模型 - 視圖 - 控制器分離的重構

為了解決上面所遺留的問題,你必須将模型與控制器角色分離。

視圖的實作代碼與前部分相同。

模型

下面的代碼例子使模型角色僅僅依賴于資料庫,而不包含任何與視圖相依賴的代碼。

using System;

using System.Collections;

using System.Data;

using System.Data.SqlClient;

public class DatabaseGateway

{

   public static DataSet GetRecordings()

   {

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

      return ds;

   }

   public static DataSet GetTracks(string recordingId)

   {

      String selectCmd =

         String.Format(

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

         recordingId);

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

      return ds;

   }

現在的代碼隻依賴于資料庫,這個類是一個優秀的資料庫的通道,它持有通路表或視圖的所用的SQL語句,其它的代碼調用一些方法來完成與資料庫的互動。

控制器

這種重構方式利用代碼隐藏機制,在負責資料通路的模型部分相對獨立的情況下,由控制器負責事件與方法的控制工作。模型的任務很明确的,它僅傳回一個DataSet對象。這種實作方式就像視圖代碼一樣,不依賴于資料是如何從資料庫中傳回的。

using System;

using System.Data;

using System.Collections;

using System.Web.UI.WebControls;

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)

      {

         DataSet ds = DatabaseGateway.GetRecordings();

         recordingSelect.DataSource = ds;

         recordingSelect.DataTextField = "title";

         recordingSelect.DataValueField = "id";

         recordingSelect.DataBind();

      }

   }

   void SubmitBtn_Click(Object sender, EventArgs e)

   {  

      DataSet ds =

         DatabaseGateway.GetTracks(

         (string)recordingSelect.SelectedItem.Value);

      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

}