3. Develop Web Application with ASP.NET MVC本場次大綱從5W1H看ASP.NET MVC什麼是MVC? 透過這樣的架構開發的應用程式有何優點?ASP.NET MVC Framework又是什麼?和ASP.NET WebForm技術不同嗎?如何利用ASP.NET MVC來開發MVC應用程式?如何撰寫出較好的Web應用程式?
4. 解決方案總是從問題而來 - Develop Web Application with ASP.NET MVC ASP.NET MVC的 5W 1HWHAT - 什麼是ASP.NET MVC?WHEN - 何時需要使用ASP.NET MVC?WHY - 為何要使用ASP.NET MVC?WHO - 誰適合來使用ASP.NET MVC?WHERE - 在些場合中需要使用ASP.NET MVC?HOW - 如何開發ASP.NET MVC 應用程式?
6. 什麼是MVC? - Develop Web Application with ASP.NET MVC MVC…是一種設計模式。MVC這個Pattern要求我們在開發程式的時候,把我們要透過程式碼達成的一個功能,在設計時切割成Model、View、Controller這三個部分(的程式碼)。每一個部分可以獨立互不干涉,但執行時可以互相合作,已達成功能,開發時亦可由不同的開發人員進行開發、同時也便於Unit Test。目的:降低程式碼之間的相依性、提高重用性便於多人開發、單元測試、降低開發成本結構清晰、利於後續維護…
8. 什麼是MVC? - Develop Web Application with ASP.NET MVC ASP.NET MVC微軟平台上新提供的MVC開發架構,透過這組類別庫,開發人員可以MVC架構來建立Web應用程式。這組MVC架構可以同時提高程式的延展性與彈性,降低.aspx頁面與後端資料庫、商業邏輯之間的相依性,達成大型專案的快速開發、高重用性、容易調整與維護的目的。
9. 什麼是ASP.NET MVC Framework- Develop Web Application with ASP.NET MVCASP.NET MVC Framework是…架構在ASP.NET技術上的一組Framework。讓開發人員得以輕鬆建立出MVC架構的應用程式。提供建構MVC應用程式所需的基礎類別、以及相關工具(Helper) 。概念上與ASP.NET WebForm並不相同,不支援事件驅動、Web Controls、或是Postback…等機制。支援了一些ASP.NET過去相當優秀的設計,例如Master-Page、MemberShip、UserControl等機制。
12. MVC三合一應用程式Protected Sub Button_GetBMI_Click(ByValsender As Object, ByVale As EventArgs) Handles Button_GetBMI.Click Dim BMI As Single Dim height, weight As Single'從UI取得身高體重 height = Me.TextBox_Height.Text weight = Me.TextBox_Weight.Text'計算BMI(主要邏輯運算) BMI = weight / (height / 100) ^ 2'顯示BMIMe.Label_Result.Text = "計算結果 BMI=" & BMI‘將資料儲存到資料庫SqlDataSource1.InsertCommand = "Insert into BmiData (Height,Weight,BMI) values (@Height,@Weight,@BMI)" SqlDataSource1.InsertParameters.Add("Height", height)SqlDataSource1.InsertParameters.Add("Weight", weight) SqlDataSource1.InsertParameters.Add("BMI", BMI)'顯示訊息If SqlDataSource1.Insert() > 0 ThenClientScript.RegisterStartupScript(Me.GetType, "", "alert('儲存成功');", True) ElseClientScript.RegisterStartupScript(Me.GetType, "", "alert('儲存失敗');", True) End If這種程式我們稱為:MVC三合一寫法『一氣呵成』、從前端殺到後端的『直搗狂龍式』寫法ClassicBmiWebAP
13. MVC三合一的問題- Develop Web Application with ASP.NET MVC在同一個事件當中, 又處理UI, 又處理邏輯, 又存取DB前端.aspx頁面與後端資料庫密不可分前端.aspx頁面與後端商業邏輯程式碼難分難捨即使具有DataAccess Class也難免保證開發人員遵循(*)牽一髮而動全身
14. MVC三合一的問題- Develop Web Application with ASP.NET MVC應該如何改進?將Business Logic獨立出來將資料庫存取部分獨立出來結果:程式碼相依性降低、可重用性提高程式碼變多?效能會提升嗎?
18. MVC的目的- Develop Web Application with ASP.NET MVC避免在同一段程式碼當中, 又處理UI, 又處理邏輯, 又存取DB…降低程式之間的相依性、提高重用性讓程式碼結構更加清晰不同的模塊可由擅長該技術的專職開發人員進行開發,降低開發成本,提高產能便於Unit Test、使TDD成為可能
30. 認識Controller- Develop Web Application with ASP.NET MVC負責接收Browser端透過HTTP GET/POST傳來的RequestUrl可決定該Request由哪一個Controller、哪一個Action來負責Controller當中可以進行各種運算、亦可能包含商業邏輯、各種演算法…等程式碼。如果有需要,可調用Model來進行後端資料庫存取的動作。最後決定由哪一個View來處理結果的呈現。同時將View需要呈現的資料透過ViewData傳遞給View。
31. 關於URL Routing- Develop Web Application with ASP.NET MVCURL Routing機制負責將Browser傳來的Request對應到Controller與Action。在這種設計架構下,我們可以用同一個『頁面』負責同一種『工作』 。可降低頁面的數量,每一個頁面(View)清楚的負責一種『功能』,不需要撰寫許多頁面負責同樣的功能(例如不同資料表的顯示)。URL直接對應到『功能』 ,在邏輯上更加直覺。http://localhost:50302/bmi/indexActionControllerWeb Site
32. 認識Controller- Develop Web Application with ASP.NET MVCController中程式碼的撰寫方式, 同名處理不同的Verbs' HTTP GET: /Bmi/IndexFunction Index() AsActionResult (…略…)Return View()EndFunction' HTTP POST: /Bmi/Index <AcceptVerbs(HttpVerbs.Post)> _FunctionIndex(ByValTxbHeightAs Single, ByValTxbWeightAs Single) As ActionResult (…略…)Return View()EndFunction使用預設的View(也就是BMI/Index.aspx)來回應從View欄位接收參數
33. 關於URL Routing- Develop Web Application with ASP.NET MVC例如,底下的URL可以用來顯示編號為17的產品:請注意Global.asax檔案(設定Url Route, 底下為預設)http://store.abc.com/product/ShowDetails/17ActionIDWeb SiteControllerroutes.MapRoute( _ "Default", _"{controller}/{action}/{id}", _New With {.controller = "Home",.action = "Index",.id = ""} _)
34. 認識Controller- Develop Web Application with ASP.NET MVCController中程式碼的撰寫方式各種ActionResultViewResult, EmptyResult, RedirectResult, JavaScriptResult, ContentResult, FileContentResult, FilePathresult, FileStreamResult, …' GET: /product/ShowDetailsFunctionShowDetails(ID As Integer) AsActionResult '取得ID '透過Data Model抓取資料庫中的內容 ‘將資料傳遞給ViewPageReturn View()EndFunction
35. Controller如何與View溝通?- Develop Web Application with ASP.NET MVC抓取ViewPage上的欄位值' POST: /Bmi/Index <AcceptVerbs(HttpVerbs.Post)> _Function Index(ByValTxbHeightAs Single, ByValTxbWeight As Single) As ActionResult (…略…)'使用預設的VIewReturn View() End Function
36. Controller如何與View溝通?- Develop Web Application with ASP.NET MVC透過ViewData將資料傳給ViewPage' POST: /Bmi/Index <AcceptVerbs(HttpVerbs.Post)> _Function Index(ByValTxbHeight As Single, ByValTxbWeight As Single) As ActionResult Dim BMI As Single Dim MyBMIAs New BMI'使用BMI類別進行運算MyBMI.Height = TxbHeightMyBMI.Weight = TxbWeight BMI = MyBMI.GetBMI()'將執行結果傳遞給ViewViewData("result") = BMI'使用預設的VIewReturn View() End Function
37. Controller如何與View溝通?- Develop Web Application with ASP.NET MVC透過ViewData將資料傳給ViewPage' POST: /Bmi/Index <AcceptVerbs(HttpVerbs.Post)> _Function Index(ByValTxbHeight As Single, ByValTxbWeight As Single) As ActionResult (…略…)Return View(Model) End Function可傳遞任何的物件給ViewPage
38. 認識Controller - Develop Web Application with ASP.NET MVC建立在Controllers資料夾中繼承自System.Web.Mvc.Controller負責回應Browser的各種Request如何從ViewPage接收參數?透過ID、透過ViewPage上的欄位如何傳遞參數給ViewPage?透過ViewData、透過ViewResult的Model參數
39. 認識ViewPage- Develop Web Application with ASP.NET MVC負責展示層UI的顯示。與商業邏輯運算、後端資料庫均無關。在這個部分當中可以有程式碼,但程式碼只應該與UI(或UI上的操作)有關,不應該有任何與商業邏輯、後端資料庫有關的任何程式碼,對於Web應用程式來說,主要就是Render出HTML與前端JavaScript操作的部分。繼承於System.Web.Mvc.ViewPage 。可透過ViewData取得來自Controller的資料。可透過Model取得來自Controller的複雜資料。具有HtmlHelper可使用,便於開發。
40. 認識ViewPage- Develop Web Application with ASP.NET MVC與過去ASP類似的程式撰寫方式可透過HTML Helper協助產生需要的Html Element不支援Web Controls可透過ViewData抓取到Controller傳遞過來的資料 <% Using Html.BeginForm() %><br/>身高:<% =Html.TextBox("TxbHeight") %><br/>體重:<% =Html.TextBox("TxbWeight") %><input type="submit" value="Calculate" /><% End Using%><% If ViewData("result")IsNot Nothing Then Response.Write("BMI:" & ViewData("result")) %>
41. 認識ViewPage- Develop Web Application with ASP.NET MVCHtml Helper支援…Html.ActionLink(linkText,ActionName,ControllerName)Html.TextBox(name)Html.TextArea(name)Html.RadioButton(name,value)Html.BeginForm()Html.Encode(value)…
46. 認識Model - Develop Web Application with ASP.NET MVC負責了實際資料庫存取的部分。這部分的程式碼負責把後端資料庫給封裝起來,讓Controller或View可以完全不(需要)知道(或不在乎)後端資料庫的長相究竟為何,只需要透過Model即可正確的存取後端資料庫。有效的隔離展示層程式碼與後端資料庫可透過Bind修飾字將ViewPage上的資料繫結到Controller的參數,以便於儲存到DBContoller中可透過ViewResult的Model參數將從DB取得的資料以物件型態傳遞給ViewPage。(請注意ViewPage須設定泛型型別)
47. 認識Model - Develop Web Application with ASP.NET MVCContoller中可透過ViewResult的Model參數將從DB取得的資料,以物件型態傳遞給ViewPage。(請注意ViewPage須設定泛型型別) Dim db As New AddressBookDBDataContext' ' HTTP GET: /AddressBook/Function Index() As ActionResult Return View(db.AddressBook.ToList) End Function
48. 認識Model - Develop Web Application with ASP.NET MVC承接的ViewPage,需要設定泛型型別,以便於取得資料<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of AddressBookMvcApp.AddressBook))" %><% For Each item In Model%> <tr> <td> <%=Html.ActionLink("Edit", "Edit", New With {.id = item.uid})%> | <%=Html.ActionLink("Details", "Details", New With {.id = item.uid})%> </td> <td> <%= Html.Encode(item.uid) %> </td> <td> <%= Html.Encode(item.cName) %> </td> <td> <%= Html.Encode(item.cTel) %> </td> <td> <%= Html.Encode(item.cMemo) %> </td> </tr> <% Next%> </table></asp:Content>
49. 認識Model - Develop Web Application with ASP.NET MVC儲存(回寫)資料時,亦可透過Bind修飾字將ViewPage上的資料繫結到Controller的參數,以便於儲存到DB。 'Post: /Home/Create<AcceptVerbs(HttpVerbs.Post)> _Function Create(<Bind(exclude:="uid")>ByValTableData As AddressBookMvcApp.AddressBook) As ActionResultdb.AddressBook.InsertOnSubmit(TableData)db.SubmitChanges() Return RedirectToAction("Index")End Function
58. 關於Unit Test- Develop Web Application with ASP.NET MVC由於View與Business Logic已經切割開來, 有助於Unit Test的進行。 <TestMethod()> Public Sub TestMethod1() Dim theBmiControllerAs New BmiController Dim theViewResult As ViewResult = theBmiController.Index(170, 70)Assert.AreEqual("24.22145", theViewResult.ViewData("result").ToString)End SubD:\MyDoc\0T.教育訓練\Microsoft MSDN講座-ASP.NET MVC\BmiMvcApp
59. 解決方案總是從問題而來 - Develop Web Application with ASP.NET MVC ASP.NET MVC的 5W 1HWHAT - 什麼是ASP.NET MVC?WHEN - 何時需要使用ASP.NET MVC?WHY - 為何要使用ASP.NET MVC?WHO - 誰適合來使用ASP.NET MVC?WHERE - 在些場合中需要使用ASP.NET MVC?HOW - 如何開發ASP.NET MVC 應用程式?
61. ASP.NET MVC相關資源筆者 BLOG http://blog.studyhost.com/筆者 RUN!PC ASP.NET 3.5 SP1-4.0專欄ASP.NET網站MVC篇:http://www.asp.net/mvc/