在ASP.NET中實現MVC模式(一)

來源:互聯網
上載者:User
asp.net 在ASP.NET中實現Model-View-Controller模式(一)



背景:



當利用ASP.NET建立Web應用程式時,基於程式的複雜性,必須把程式分割成不同的部分以減少代碼的重複及減少日後變革時所引起的改動。



實現策略:



為瞭解釋如何在ASP.NET中實現(MVC)模型-視圖-控制器模式,以及說明將軟體分離成模型、視圖、及控制器角色的好處,在此以一個樣本程式為例進行說明。這個樣本程式是一個帶有下拉框的單頁程式,它的功能是顯示資料庫中的資料。如下圖。





當使用者在下拉框中選擇了一個記錄,並單擊Submit按鈕的時候,程式從資料庫中搜尋與選中記錄相關的資料庫記錄,並以列表的形式顯示出來。下面,將以三種不同的實現方式進行實現。



單頁模式



在ASP.NET中有許多解決這個問題的辦法,其中最簡單也是最直接的辦法就是把所有的代碼都放到一個檔案中,並起名為Solution.aspx,實現代碼如下:

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<html>

<head>

<title>start</title>

<script language="c#" runat="server">

void Page_Load(object sender, System.EventArgs e)

{

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

}

</script>

</head>

<body>

<form id="start" method="post" runat="server">

<h3>Recordings</h3>

Select a Recording:<br />

<asp:dropdownlist id="recordingSelect" runat="server" />

<asp:button runat="server" text="Submit" OnClick="SubmitBtn_Click" />

<p/>

<asp:datagrid id="MyDataGrid" runat="server" width="700"

backcolor="#ccccff" bordercolor="black" showfooter="false"

cellpadding="3" cellspacing="0" font-name="Verdana"

font-size="8pt" headerstyle-backcolor="#aaaadd"

enableviewstate="false" />

</form>

</body>

</html>



這個實現檔案包含了模型、視圖、控制器這三種角色,但是沒有將它們分割為不同的檔案或類。其中的視圖對象用HTML實現,用一個資料繫結控制項來顯示從資料庫返回的DataSet中的資料。模型角色在Page_Load 和 SubmitBtn_Click函數中實現。而控制器角色並沒有顯式的實現,而是由ASP.NET隱式實現。程式運行時,當使用者發出頁面的請求,頁面隨著使用者的選擇更新。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.