Tổng quan về ASP.NET MVC...
Transcript of Tổng quan về ASP.NET MVC...
![Page 1: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/1.jpg)
Bài số 3
Tổng quan về ASP.NET MVC Framework
Table of Contents
1 Tại sao sử dụng ASP.NET MVC.......................................................................................... 21.1 ASP.NET MVC là gì................................................................................................................................2
1.1.1 Mô hình MVC cơ bản................................................................................................................................... 2
1.1.2 Một vài đặc tính trong ASP.NET MVC................................................................................................... 2
1.2 Sự khác biệt với WebForm....................................................................................................................3
2 Ví dụ xây dựng ứng dụng với ASP.NET MVC Framework................................................ 4
2.1 Tạo Project với ASP.NET MVC Web Application...............................................................................................4
2.2 Tim hiểu định tuyến URL............................................................................................................................................. 8
2.3 Xây dựng mô hình dứ liệu...........................................................................................................................................9
2.3.1 Tao cơ sở dử liệu...........................................................................................................................................9
2.3.2 Sử dụng mô hình LINQ to SQL................................................................................................................ 10
2.4 Tim hiểu về Controllers............................................................................................................................................. 14
2.5 Tim hiểu về Views.........................................................................................................................................................16
2.6 Tim hiểu về Models..................................................................................................................................................... 18
2.7 Câu trúc Views\Shared\Site.Master..................................................................................................................... 20
2.8 Kêtquả............................................................................................................................................................................. 21
3 Câu hỏi ôn tập......................................................................................................................214 Tài liệu tham khảo......................................................................................................................... 22
![Page 2: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/2.jpg)
1 Tại sao sử dụng ASP.NET MVC
1.1.1 Mô hình MVC cơ bản
MVC viết tắt của các chữ cái đầu của Models, Views, Controllers. MVC chia giao diện UI thành 3 phần tương ứng: đầu vào của controller là các điều khiển thông qua HTTP request, model chứa các mien logic, view là những thứ được sinh ra trả về cho trình duyệt.
Lợi ích của việc dùng phương pháp MVC là sự phân đoạn rõ ràng giữa models, views, controllers bên trong ứng dụng. Cấu trúc sạch sẽ giúp cho việc kiểm tra lỗi ứng dụng trở nên dễ dàng hơn.
1.1.2 Một vài đặc tính trong ASP.NET MVC
• Tách rõ ràng các mối liên quan, mở khả năng test TDD (test driven developer). Có the test unit trong ứng dụng mà không cần phải chạy Controllers cùng với tiến trình của ASP.NET và có thể dùng bất kỳ một unit testing framework nào như NUnit, MBUnit, MS Test, v.v...
• Có khả năng mở rộng, mọi thứ trong MVC được thiết kế cho phép dễ dàng thay thế/tùy biến ( ví dụ: có thể lựa chọn sử đụng engine view riêng, routing policy, parameter serialization, v.v..
• Bao gồm một ánh xạ URL mạnh mẽ cho phép xây dựng ứng dụng với những URL sạch, các URL không cần cs phần mờ rộng ( ví dụ: có thể ánh xạ địa chi /Products/Edit/4 để thực hiện hành động “Edit” của lóp điều khiển ProductControllers hoặc ánh xạ địa chỉ /Blog/SomeTopic để thực hiện hành động “Display Topic” của lóp điều khiển BlogEngineController)
• ASP.NET MVC Framework cũng hỗ trợ những file ASP.NET như .ASPX .ASCX và .Master, đánh dấu các tập tin này như một “view template” ( có thể dễ dàng dùng các tính năng của ASP.NET như lồng các trang Master, <%= %> snippets, mô tả server controls, template, data-binding, localization, v.v... ). Tuy nhiên sẽ
Figure 1. Mô hình MVC cơ bản
Microsoft Vietnam -D P E Team IBài sổ 3: Tỏng quan về ASP.NET MVC Framework 2
![Page 3: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/3.jpg)
không còn postback và interactive back server và thay vào đó là interactive end-user tới một Controller class ( không còn viewstate, page lifecycle )
• ASP.NET MVC Framework hỗ trợ đầy đủ các tính năng bão mật của ASP.NET như forms/windows authenticate, URL authorization, membership/roles, output và data caching, session/profile state, configuration system, provider architecture v.v...
1.2 Sự khác biệt với WebForm
ASP.NET WebForm sử dụng ViewState để quản lý, các trang ASP.NET đều có lifecycle, postback và dùng các web controls, các events để thực hiện các hành động cho UI khi có sự tương tác với người dùng nên hầu hết ASP.NET WebForm xử lý chậm.
ASP.NET MVC Framework chia ra thành 3 phần: Models, Views, Controllers. Mọi tương tác của người dùng với Views sẽ được thực hiện hành động trong Controllers, không còn postback, không còn lifecycle không còn events.
Việc kiểm tra ( test ), gỡ lỗi ( debug ) với ASP.NET đều phải chạy tất cả các tiến trình của ASP.NET và mọi sự thay đổi ID của bất kỳ controls nào cũng ảnh hường đến ứng dụng. Đối với ASP.NET MVC Framework thì việc có thể sử dụng các unit test có thể thẩm định rất dễ dàng các Controller thực hiện như thế nào.
Tính năng ASP.NET 2.0 ASP.NET MVC
Kiến trúc chương trình Kiến trúc mô hình WebForm -> Business -> Database
Kiến trúc sử dụng việc phân chia chương trình thành Controllers, Models, Views
Cú pháp chương trình Sử dụng cú pháp của webform, tất các sự kiện và controls do server quản lý
Các sự kiện được điều khiển bởi controllers, các controls không do server do server quản lý
Truy cập dừ liệu Sử dụng hầu hết các công nghệ truy cập dừ liệu trong ứng dụng
Phần lớn dùng LINQ to SQL class để tạo mô hình truy cập đối tượng
Debug Debug chương trình phải thực hiện tất cả bao gồm các lớp truy cập dừ liệu, sự hiển thị, điều khiển các controls
Debug có thể sử dụng các unit test kiểm tra các phương thức trong controller
Tốc độ phân tải Tốc độ phân tải chậm khi trong trang có quá nhiều các controls vì ViewState quá lớn
Phân tải nhanh hơn do không phải quản lý ViewState để quản lý các control trong trang
Tương tác với javascript Tương tác với javascript khó khăn vì các controls được điều khiển bởi server
Tương tác với javascript dễ dàng vì các đối tượng không do server quản lý điều khiển không khó
URL Address Cấu trúc địa chỉ URL có dạng <filename>.aspx?&<các tham số>
Cấu trúc địa chỉ rành mạch theo dạng Controllers/Action/Id
Microsoft Vietnam -D P E Team IBài sỗ 3: Tỏng quan về ASP.NET MVC Framework 3
![Page 4: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/4.jpg)
2 Ví dụ xây dựng ứng dụng với ASP.NET MVC Framework
Tính năng ASP.NET MVC Framework hiện giờ mới là bản Beta trong .NET Framework 3.5. Đe xây dựng ứng dụng với ASP.NET MVC Framework cần có môi trường hoạt động .NET Framework 3.5 (cụ the chương trinh sau sẽ xây dựng với Visual Studio 2008 ), tiếp theo cần một MVC Framework. Mặc định trong Visual Studio 2008 chưa có sẵn ASP.NET MVC Web Applications. Có thể download ASP.NET MVC Framework tại địa chi http://www.microsoft.com/downloads/details.aspx ?Familyĩd=A24DlE00-CD35-4F66-BAA0- 2362BDDE0766&displaylang=en. Cài đặt Visual Studio 2008 sau đó cài đặt ASP.NET MVC Framework. Bây giờ có thể bắt đầu xây dựng ứng dụng với MVC.
2.1 Tạo Project với ASP.NET MVC Web Application
Trong chương trình Visual Studio 2008 đã cài đặt ASP.NET MVC Framework: File -> New Project -> Windows c# ASP.NET MVC Web Application ( xem Figure 2).
S ta rt P a g e - M icro soft V isu a l S tu d io
F ie Edit View Tools T e s t W indow Help
a - i * u aW \ s t a r t P a g e
c .C o n ten t
I Microsoft*
VisuRecent Projects
XẲHỈTest
P ro ject types:
O pen:C rea te :
Pr.Kr<
Getting started
W hat's new in Visual CC rea te Your First Appb How Do I . . . ?Learn Visual C~ Download Additional Cx MSDN Forums Visual C - D eveloper Q E x tend Visual Stu<±o
E Visual C * V isu a l S tu d io i n s t a l l e d t e m p l a t e sW indows
î W eb JçJ] Windows Forms Application ¿73]C lass Library
S m art Device , ASP. NET W eb Appfication gèf ASP.NET W eb Service ApplicationS3 Office 1 Ç^jWPF Application (“c*; WPF Browser Application
D a tab ase “^ C o n s o le Application 'ty f Excel 2007 W orkbookR eporbng „ £ Outlook 2 007 Add-m '-§^WCF Service ApplicationT est ££?W ord 2007 Docum ent Windows Forms Control LibraryWCFWorkflow
& O ther P ro iec t T y œ s M y T e m p la t e si±j T e s t Pro jects
k_J]S earch Online T em p la tes ...
A p ro jec t for c reating an application using th e ASP.NET MVC fram ew ork (B eta) (.NET Framework 3.5)
Name:
Location:
Solution Name:
D:\ProjectsVHiTest
Z]V I B row se ... j
HiTest 0 C rea te d rec to ry for solution
Figure 2. Tạo một Projects ASP.NET MVC
Khi tạo một ASP.NET MVC Framework thì một hộp thoại Unit Test xuất hiện. Chọn Yes nếu muốn tạo một Project Test, chọn No nếu không muốn tạo một Unit Test. ( xem Figure 3)
Microsoft Vietnam -D P E Team IBài sỏ 3: Tông quan về ASP.NET MVC Framework
![Page 5: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/5.jpg)
V/"* storl Pane Microsoft Vĩsuol StudioFile Edit View
i a o - kid- & IT ools T e s t
Í*W indow Help
c .C o n te n t
Sta rt P age
^ Microsoft"4* Visual Studio 2008
1 2 2 2 2 2 2
i ẳ H T e s t
O p e n : P ro je cC re a te : P ro je c
Ị G etting s ta rte d
C r e a t e U n it T e s t P r o je c t
Would you like to c re a te a unit te s t p ro je ct fo r thts application?
( • ) Y e s , c r e a t e a u n it t e s t p r o je c t
T e s t p r o je c t n a m e :
H T T estT es ts 1T e s t f ra m e w o rk :
Visual S tu d io U nit T e s t V .Ị
1 Visual s t u d o U nit T e s t sA dditional In fo
W hat’s n ew in Visual C # ?C r e a te Y our F irs t A pplicatx How Do I . . . ?L e a rn Visual C ~D o w n lo ad A dditional C o n te MSDN F orum s Visual C # D e v e lo p e r C e n te r E x te n d Visual S tud io
o N o , d o n o t c r e a te a u n it t e s t p r o je c t
C ancel
A- v id eo p o d c a s t w hich wiB t
mic D o e s n o t Do in th is s ix ữ
th e QA te a m 's s e c r e t tec h i
ta lk s a b o u t th e ra t io n a le b e fu tu re to co n s id e r w h a t t h e
t h a t ta k e s a d v a n ta g e o f rr y in v o lv ed in w riting multi -fr
______________________________________________________________ ị a n e w im p lem en ta tio n o f dla n g u a g e ru n n m g o n .NET. I t s u p p o r t s a n in te r a c tiv e co n so le w ith fully d y n am ic com pilation . In te g ra t i F ram ew o rk m ak e s all .NET lib raries e asily av a ila b le to P y th o n p ro g ra m m e rs .Dynam ic Lan g u ag e Runtim e Beta availab le for download.W ed , 10 D ec 2 0 0 8 2 2 :4 0 :0 0 z - T h e D ynam ic L a n g u a g e R untim e e n a b le s la n g u a g e d e v e lo p e rs to m or la n g u a g e s fo r th e .NET p la tfo rm . I t p ro v id e s DLR c o m p o n e n ts , a n d o p e n s o u rc e im p le m e n ta tio n s o f Ir d o c u m e n ta tio n , a n d sa m p le s .
Figure 3. Tạo Unit Test cho ASP.NETMVC
Sau khi một ứng dụng ASP.NET MVC Web Application được tạo, nhìn vào trong mục Solution Explorer sẽ thấy xuất hiện mặc định 3 thư mục: Models, Views, Controllers chứa các đối tượng tương ứng với các thành phần Models, Views, Controllers trong mô hình MVC.
Mờ rộng folder Controllers sẽ thấy HomeController.es, mờ rộng Views sẽ thấy folder Home, Shared và Account. Mở rộng folder Home sẽ thấy About.aspx và Index.aspx ( xem hình Figure 4 )
Microsoft Vietnam —DPE Team IJBài sổ 3: Tỏng quan về ASP.NET MVC Framework 5
![Page 6: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/6.jpg)
Solution Explorer-Solution'BanHang'(2 pr... ▼ -a X
a j a pSolution 'BanHang' (2 projects)
B BanHang
SI S i Properties ffl References Q LS App_Data
S) I j (S ContentS ■ L3r Controllers
^ AccountController.es 'i )̂ HomeController.es
□ Models IB □ Scripts S Views
§<5
•6
Ê3 AccountIB ¿ j ChangePassword.aspx(B ¿H ChangePasswordSuccess.aspxffi Login.aspxffl [HU Register.aspx
G3 HomeSi ID About, aspxSI m Index.aspx
3 \Jjr SharedSI lHH Error.aspxSI 33 LoginUserControl.ascxSI n Site.Master;jj» Web.config
GÌ jif] Default.aspxạ Global.asax
ijj* Web.configB BanHang.Tests
SB PropertiesSI Referencesffl Cà Controllers
App.configAuthoringTests.txt
Figure 4. Solution Explorer MVC
Chạy ứng dụng bang cách an F5. Neu là ứng dụng mới tạo lần đầu thì sẽ có thông báo hỏi có cho phép mở chế độ Debug hay không? Neu đồng ý chọn “Modify the Web.config file to enable debugging”, ko muon debug chọn “Run without debugging”. ( xem Figure 5).
Microsoft Vietnam —DPE Team \Bui SO 3: Tỏng quan v ề ASP.NET MVC Framework
![Page 7: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/7.jpg)
Tools Test Window Help
Any CPU c.Content
Idi0'2008
MSDN: Visual c# Headlines
10-4 Episode 1: Working with the Visual Studio 2010 CTP VPC
Solution Explorer - Solution 'HiTest' (2 proj...
a j i» SM»J Solution 'HiTest' (2 projects)
Ei ,'ỊỊ HfTest
D eb u g g in g Not E n a b le d 7 X
The page cannotbe run in debug mode because debugging is not enabled in the Web.config file . What would you like to do?
Modify the Web.config file to enable debugging.
; , Debugging should be disabled in theWeb.config file beforedeploying the Web site to a production environment.
O without debugging. (Equivalent to Ctrl+F5)
ffiB
asffi
œaffiffl
:~JL Properties •wi References [^ j AppJData 1_J Content a Controllers r J Models r~3 Scripts I i Views 1̂ 1 Default.aspx
1 Global.asax Web.config
OK Cancel I
see m a t L1IMỤ querre rca rranow you to sraeTsretncnETSTncnrrrasKS normally invo lved in
Iron PythonThu, 18 Sep 2008 08:40:08 z - IronPython 2.0 Has shipped. IronPython is a new imple language running on .NET. I t supports an interactive console with fully dynamic compile Framework makes all .NET libraries easily available to Python programmers.Dynamic Language Runtime Beta available for download.Wed, 10 Dec 2008 22:40:00 z -The Dynamic Language Runtime enables language dev languages for the .NET platform. I t provides DLR components, and open source implen documentation, and samples.
Figure 5. MỞ Debug Irung Web.config ASP.NETMVC
Ket quả khi chạy ứng dụng ( xem Figure 6) là ứng dụng được load vào browser. Trong ví dụ này chỉ có 2 trang là Index và About.
B 3 HiTest.Tests I® Properties B l 5 References
•O HiTest•t_3 Microsoft.VisualStudio.Qual -O System •O System.Core -O System.Web.Abstractions •O System.Web.Extensions •O System.Web.Mvc •CJ System.Web.Routing
1/^ ControllersHomeControllerTest.cs
App.config AuthoringTests.txt
I to r Page - Mozilla FircfoxE»le Edit Ytew H istory Bookm arks Tools Help
- O X ¿ ¡ 5 I Q |h t tp : /A > c a f io s t : 1 7 2 7 /
_J y Most Visited 3̂ ̂Getting Started Latest Headlines
'Cĩ ~ 1 llcl-l<■
ASP.NET M» r - ~. ASP.NET My f T Download d * ASP.NET My f- Ì ASP.NET MV - Understand! I • Home —O
My Sample MVC Applicationc L o g in 3
A b o u t U s
Welcome to ASP.NET MVC!
To learn more about ASP.NET MVC visit http;//asp.net/mvc.
My Sample MVC Application © Copyright 2008
Microsoft Vielnum —DPE Team IjBui so 3: Tổng quan về ASP.NET MVC Framework
![Page 8: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/8.jpg)
Figure 6. Thực thi ứng dụng mẫu ASP.NET MVC
2.2 Tìm hiểu định tuyến URL
Browser yêu cầu một địa chi từ controller action trong ASP.NET MVC Framework được gọi là định tuyến URL ( URL routing). Url routing sẽ chỉ định request tới controller action. URL routing sử dụng một bảng định tuyến để điều khiển các request. Bảng định tuyến được tạo khi ứng dụng bắt đầu được chạy lần đầu tiên. Bảng định tuyến được thiết lập trong file Global.asax
using System;using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;
namespace HiTest {
// Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication {
public static void RegisterRoutes (Rc Let routes){
routes.IgnoreRoute("{resource}.axd/{*pathlnfo}");
name
routes-MapRoute( "Default",
"{controller}/{action}/{id}", parameters
new { controller = "Home", action = "Index", id = "" } //Parameter defaults
) ;
// Route
// URL with
1
protected void Application_Start(){
RegisterRoutes( .Routes);
Khi ứng dụng chạy lần đầu tiên, phương thúc Application_Start() được gọi, phương thức này gọi một phương thức khác RegisterRoutes(RouteTable.Routes) để tạo ra bảng định tuyến.
Định tuyến mặc định chia một request thành 1 phân đoạn, mỗi phân đoạn nằm giữa 2 dan Phân đoạn đầu tiên chứa tên một controller, phân đoạn thứ 2 chứa tên controller actỉon, phân đoạn thứ 3 là tham số đầu vào của controller action.
Ví dụ: với địa chi /Product/Details/3 được hiểu là:
Controller = ProductController Action = Detail Id = 3
Controller mặc định sẽ là HomeController, Action mặc định là Index, Id mặc định là -> http://localhost: 1727/
Ví dụ: với địa chỉ /Employee:
Microsoft Vietnam —DPE Team IJBài sổ 3: Tỏng quan về ASP.NET MVC Framework 8
![Page 9: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/9.jpg)
Controller = EmployeeController Action = Index Id = ""
2.3 Xây dựng mô hình dữ liệu
2.3.1 Tạo cd sở dữ liệu
Từ AppJData click phải chuột chọn Add -> New Item -> SQL Server Database đặt tên Databasemdf
Odd N e w H e m - Ban Hang 7 X
Categories: Templates: m BS Visual C# Visual Studio installed templates
CodeData J SQL Server Database Jj] Text FileGeneral j/ ] XML File XML Schema
S. WebWindows Forms My TemplatesWPF
. j Search Online Templates...ReportingWorkflow
An empty SQL Server database
Name: Databaselmdf ]
I Add 1 Cancel Ir y n n n j r l u i ' i r t r i n u — r a r
Figure 7. Tạo cơ sở dữ liệu Database.mdf trong App_Data
Trong cơ sở dữ liệu Database.mdf tạo 2 table: ( xem Figure 8, Figure 9 )
Microsoft Vietnam -D P E Team IBài sỏ 3: Tông quan về ASP.NET MVC Framework
![Page 10: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/10.jpg)
BanH anq - M icroso ft V isu a l S tu d io
File Ecfct Vtew P ro je c t Build D ebug D a ta
S ' ' 3 a m ể [£ H a ã a .
Table D esigner Tools T e s t
► D ebug
W indow Help
- Any CPU • c .C o n te n t • <5:5* H i*
dbo-Tab*e2- T__DATABASC.MDT)* stvtp
C o t ^ r Name D a ta T ype
» ? Id I int □ JT enSanPham
DonG*a
SoLuong
LoaiSanPham
Column P ro p e rtie s
n v a r ch a r (300)
f loa t
int
Int
0000n
I M U . - ] ------------------------------------------------------------------------------------------------------□ ( G e n e r a l )
(Nam e)
A fow N ufeId
D a ta T ype in tD efau lt V alue o r Binding
El T a b le D e s ig n e r
<d a ta b a s e d e fa u lt»
0 C om pu ted Column Specification
C o n d en sed D a ta T ype n tDesuipUu«i
0
□
F u l- te x t Specification NoH as Non-SQL S e rv e r Subscriber
Id en tity Specification Yes
(Is Id en tity ) /*""
Id en tity In c re m e n t »Id e n tity S e e d I u
flm !<Untih<)
Figure 8. Bảng SanPham trong cơ sở dữ liệu Database.mdf
B a n H ang - M ic r o s o f t V is u a l S tu d io
File Edit View P ro je c t Budd D ebug D a ta T able D esigner Tools T e s t W indow Help
.3 ' Jj H ► D ebug - A nyCPU
[T| =3 3 & □ ;
y-l d b o .L o d (SdnP ...D A T A B A SE . M D F) s t a r t P a g e
J ÿ c .C on te n t
D a ta T ype
f w Id int □ ]TenLoaiSanPham nvarchar(lO O ) I'd
□
Column P ro p e rtie s
IẼÌ1ỈI ]d efau l
E l C om pu ted Column Specification
C o n d en sed D a ta T ype
Description
I D eterm inistic
I I DT5-published
E l F u l- te x t Specification
■ H as Non SQL S erver Su
□ Id en tity S ped fica tion
(Is Id en tity )
Id en tity In a e m e n t
Id e n tity S eed
■ In d ex ab le
■ M erge-published
N o t For R eplication
ÕInoNo
Figure 9. Bảng LoaiSanPham trong cơ sở dữ liệu Database.mdf
2.3.2 Sử dụng mô hình LINQ to SQL
Trong Solution Explorer click phải chuột vảo Models -> Add -> New Item ->LINQ to SQL Classes (Figure 10)
Microsoft VieCnum —DPE Team IBài su 3: Tỏng quun về ASP.NET MVC Framework 10
![Page 11: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/11.jpg)
</* BanHang - Microsoft V isual Studio
Fite Edit View Project Budd Debug Tools T est Window Help
• jp v JiJ v 3 3 ► Debugg . S t a r t P a g e
Any CPU - J ÿ c .C ontent
rr
i
4 ^ , ' Microsoft*
* Visual Studioc 2008
Solution Explorer - SoL
f t E T »Solution BanHanç
(3 ^ B an H an gLtl :m Propertie ¡♦I Refer enc
Recent Projects
J j BanHang
[¿ÄHTest
Open:C reate:
Rdd Neui Item - BanHang
Categories: Templates:
Getting Started
W hat's new in VisuaC reate Your R rst Aj How Do I . .. ?Learn Visual Cif Download Additiona M5DN Forums Visual C z Devetopei Extend Visual Studic
Q Visual C # [£: MVC View User Control ¿3] AJAX Cfcent Behavior
Code 3 JAJAX Client Control 3 jA JA X C IentU brary
Data ! ~] AJAX M aster Page AJAX Web FormGeneral AJAX-enabled WCF Service ■V] Application M anifest F ie
ffl Web c ^ | Assembly Information File ^ B r o w s e r =ileWindows Forms c^J Class ^ Class DiagramWPF c*} Code File j y j DataSetReportingWorkflow
T ? Debugger Visualizer
HTM Page Interface
|^ | Generic H ander
Installer Class¿ jJJS c n p t Fie
" / ¿ LINQ to SQL C lasses') Nested Master Page
H3 k e p o rt J ¿ j Report Wizard
Resources Rle Site Map^ S k i n File I J SQL Server D atabase
A D Style Sheet =1 Text File
LINQ to SQL d a sse s mapped to relational objects.
^ Da taC lassesj dbmTj
Figure 10. Tao LINQ to SQL Classes
Microsoft Vietnam —DPE Team I Bui sô 3: Tông quun vê ASP.NET MVC Framework 11
![Page 12: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/12.jpg)
Từ Server Explorer -> Kéo thả 2 tables LoaiSanPham, SanPham vào file DataClasses.dbmI
Bon Han g - M icrosoft V isu a l S tu d io - Æ* X
File Edit View P ro jec t Build D ebug Tools T e s t Window Help
. J3 - - 3 £ & * ► f*buoS erv e r Explorer T ? X
33 %1Ế
B
S Ut D a ta b a se .m d f
$ [_ J D a ta b a se D iagram s
S ^ 3 TablesJ LoaiSc'-Pham
j u2 ] TenLoaiSanPham
" 3 SanPham
SI IdS 3 T enSanPham [ | ] D onG a GO SoLuong
S 3 LoaiSanPham
V*ws$ □ S to red P ro ced u res$ □ FunctionsS □ Synonym s
a LA T ypesa U Assem blies
.*5^ S ervers
a 4 g'3* ^
S erv e r Explorer
R eady
T he O b jec t R e la tio n a l D e s ig re r a llo w s y o u to v isual c la s s e s In y o u r c o d e .
S e rv e rE x p lo re rT o o lb o x
C re a te m e th o d s by d ra g g in g item s from
S e rv e r E xp lo rer itolesign surface.
A
Solution E xplorer - Solution "BanHang' (2 p r . .. ▼
¡a j > a a m »!=| B a n H a n g
ffl P ro p er b e s
a R e fe re n c e s S xJi App_D ata
S I j j D a ta b a se .m d f ffl [ _ J C o n ten t
E) LJS' C on tro le rs^ AccountControU er.cs
cJSj) H om eC on tro le r.es SanPham C ontro ller.es
B Models
»■ Ia f a sen p ts -
1=1 Views
5 Ld A ccounta £U C h an g eP assw o rd .a sp xa I d C h angeP assw ordS uccess .ca ¿2 i Login, asp xa R eg is te r.a sp x
e L J r H o m e
a q ] A bout, asp x
a ¿ l i In d e x .a sp x S Ld SanPham
a liiJ In d e x .a sp x
| B LJ S hareda ~]j Err o r. asp x
a .3- L oginU serC ontrol.ascxa [ j S ite .M aster
W eb.config ffi D efau lt, a sp x
El G lobal.asaxli£j) G Iobal.asax .es W eb.config
¡3 ^ B anH ang .T ests , l+i -^1 Prnnertw*:
Figure 10. Tạo file DataClasses.dbml sử dụng 2 bảng LoaiSanPham và SanPham
Trong file DataCIasses.dbml click phải chuột chọn Add -ỳ Association để tạo liên kết giữa 2 table. (Figure 11)
Microsoft Vieínum —DPE Team IBài su 3: Tỏng quun về ASP.NET MVC Framework 12
![Page 13: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/13.jpg)
<✓» HanHrinn M icm so ft V isu a l S tu d io
File Edit View P ro jec t BuM D ebug Tools T e s t Window M dp
.j] - _iJ - A ề» -J - ► Debu9D d t d C l a s s e s ^ J b m r s ta r t P ag e
* Jỳ L ogn
S e rv e r E xplorer -w
S3 t*,«le o ' D ata C onnections
fci 0 ^ D a ta b a se .m d f* [ ^ j D a ta b a se D iagram s
3 □ T ab les$■ "ZD LoaiSanPham
lU IdT l TenLoaiSanPham
Q 3 SanPhamGD IdT l T enSanPham (Tl DonGia 3 S o tu o n g m LoaiSanPham
a C 3 Views ffl C l S to re d P ro ced u res £ [_ J Functions a Q Synonym s ffl □ T y p es dd Q j Assem blies
Q , ^ | S ervers a *§ g io d n h
■^••■nstÆWn - ^ S e r v e r Explorer
Ready
L o a iS a n P h a m
s P ro p e r tie s
t ^ I djjf* T enLoalSẽnPham
S a n P h a m © ]
B P ro p e r tie s
t ấ l di j ? T enSanPham
D onG iaS oL uong
'*j* L oaiSanPham
R s s o c i a t i o n E d i t o r
Association P roperties :
▼ X : Solution E xp lo re r-S o lu tio n B a n H a n g '(2 p r . . . ~ 1 X
a I a I El a I ȋ BanHang
I P ro p e rtie s - 1 R e fe re n c e s
__ Ann Hafa___
Child C lass:
~ h : SanPham 10
LoaiSanPham P ro p e rtie s SanPham P ro p erties
Id
I OK I [_ Cancel J- ạ —va s an p n am -----------------------------
a oj In d e x .a sp x a \& S hared
l±J ¿» ] C rro r.esp x±~ LoginU serC ontrol.ascxa ị’ LoginUserCor
ffl □ S ite .M aster i£^> W eb.config
a __l] D e fa i i t .a s p x B G lobal.asax
^ G loba l.asax .es__ _ y W eb .con fig
B anH ang .T ests
J±L
'̂ 1 Prrvwfú**;J-il"
Figure 11. Tạo liên kết giữa các bảng trong DataClasses.dbmỉ
Ket quả được như Figure 12 dưới đây.
Ban Hang - Microsoft V isua l studio
File Edit View Project Build Debug Tools Test Window Help
*> ’ ► Debug » Any CPU
V' DataClasses.dbml* start PageH --------------------------------------------------------
- J ỳ c.Content
Figure 12. cấu trúc của DataClasses.dbml
Microsoft Vielnum —DPE Teum I Bài so 3: Tung quan về ASP.NET MVC Framework 13
![Page 14: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/14.jpg)
2.4 Tìm hiểu về Controllers
Controller chịu trách nhiệm điều khiển các tương tác của người dùng bên trong ứng dụng MVC. Controller sẽ quyết định cái gì được trả về cho người dùng khi người dùng tạo ra một request trên browser.
Một controller là một class ( c# class hoặc VB class). Trong ví dụ ứng dụng ASP.NET MVC Web Application mẫu luôn tồn tại 2 controller là AccountController.es và HomeControIIer.es nằm trong folder Controllers
HomeController.es
using System;using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax;
namespace HiTest.Controllers {
[HandleError]public class HomeController : Controller {
public Index 0{
ViewData["Title"] = "Home Page";ViewData["Message"] = "Welcome to ASP.NET MVC!";
return ViewO;I
public ActionResuit About 0I
ViewData["Title"] = "About Page";
return ViewO;1
I}
Trong HomeController.es CÓ 2 phương thức là IndexO và About(). Hai phương thức này là 2 action trong controller HomeControlIer.es nó thực hiện khi được gọi bằng địa chỉ /Home/Index và /Home/About. Bất kỳ phương thức nào có thuộc tính public đều là một action trong controller.
Tạo một Controller mới
Trong folder Controllers phải chuột chọn Add -> New Item -> MVC Controller Class ( Figure 13)
Microsoft VieCnum —DPE Team IBài SU 3: Tỏng quun về ASP.NET MVC Framework 14
![Page 15: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/15.jpg)
Rdd Ne LU Item - Ban Hang ? X
Categories: Templates: m □
& Visual C S
Code Data General
ffl WebWindows Forms WPFReportingWorkflow
visual btuoto installer templates
¡rrf] Web Form j : Web User Controli t ] MVC Controller Class 'J * n ^ ^ ie w Master Page ill) MVC View User Control ¿-SjAJAX Client Control
n AJAX Master PageAJAX-enabled WCF Service
erf] Assembly Information File Class Code File
^Debugger Visualizer HTML Page
1 » . r_____________________________________
I " ! Master Page l|2l Web Content Form ~ | MVC View Content Page ¡nil MVC View Page .3 ] AJAX Client Behavior SjjA JAX Client Library ¡f ]̂ AJAX Web Form
Application Manifest File ^ B ro w se r File ^¡j Class Diagram [|3| DataSet ^ Generic Handler ¡jä] Installer Class
MVC Application Controller Class (Beta) (ASP.NET MVC Framework requires Controller names to be suffixed with "Controller")
Name: f SanPhamConfr oller, es
Add Cancel
Figure 13. Tạo controller tên là SanPhamController.es
SanPhamContxoller.es
using System;using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using BanHang.Models;
namespace BanHang.Controllers {
public class Sanl-hamControllei : Controller {
DataClassesDataContext data = new DataClassesDataContext();
public Index(){
>
// Add action logic here ViewData["Title"] = "Sản phẩm";
return RedirectToAction("DanhMucLoaiSanPham");
public I DanhMucLoaiSanPham(){
// Code cua ban o dayViewData["Title"] = "Eanh muç loaị San phâm";
< > Isp = data.LoaiSanPhams.ToList();
return View("DanhMucLoaiSanPham", Isp);}
public DanhSachSanPham(string loaisanpham){
ViewData["Title"] = "Canh sach San phâm trong loai San phâm";Microsoft Vielnum —DPE Team \Bài su 3: Tổng quan v ề ASP.NET MVC Framework
![Page 16: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/16.jpg)
< > sp = data.LaySanPhamTuLoaiSanPham(loaisanpham);
return View("DanhSachSanPham", sp);}
public ChiTietSanPham(int id)I
ViewData["Title"] = "Chi tiêt San phâm";
ctsp = data.LaySanPhamQualD(id);
return view("ChiTietSanPham", ctsp);1
I}
2.5 Tìm hiểu về Views
Trong controller HomeController.es, cả hai phương thức IndexO và About() đều trả về một view. Một view chứa các thè HTML và được trả về cho browser. Trong mô hình MVC thì một view tương ứng với một trang .aspx trong WebForm.
View phải được tạo đúng vị trí đường dẫn. Ví dụ với controller HomeController.es thì hành động HomeController.IndexO trả về một view nằm ờ vị trí đường dẫn \Views\Home\Index.aspx và HomeController.AboutO sẽ trả về một view nằm ờ vị trí đường dẫn \Views\Home\About.aspx
View About.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site-Master" AutoEventWireup="true" CodeBehind=”About.aspx.cs"Inherits="HiTest-Views.Home-About" %>
<asp:Content ID="aboutContent" ContentPlaceHolderID=”MainContent" runat="server"> <h2>About Us</h2><p>
TODO: Put <em>about</em> content here.</p>
</asp:Content>
View Index.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site-Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs"Inherits="HiTest.Views.Home.Index" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h2><%= Html. Encode (ViewData [ "Message" ] ) %X/h2><p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p></asp:Content>
Tat cả các thuộc tính nằm giữa 2 thẻ <asp:Content></asp:Content> đều có định dạng HTML và có thể tùy ý sửa đổi theo ý muốn.
Tạo view cho controller SanPhamController.es, trong SanPhamController.es có 4 phương thức public là Index(), DanhMucLoaiSanPhamO, DanhSachSanPhamO và ChiTietSanPhamO nên trong Views phải tạo 4 view tương ứng là Index.aspx, DanhMucLoaiSanPham.aspx, DanhSachSanPham.aspx, ChiTietSanPham.aspx bằng cách từ
Microsoft Vietnam -D P E Team IBài sổ 3: Tỏng quan về ASP.NET MVC Framework 16
![Page 17: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/17.jpg)
folder Views click phải chuột chọn Add -> New Folder nhập tên folder mới tạo là SanPham. Từ folder SanPham click phải chuột chọn Add -> View... (Figure 14) (ví dụ tạo view DanhMucLoaiSanPham)
R dd VieLU ? X
View name:
DanhMucLoaiSanPhaml
Ỉ~1 Create a strongly-typed view
View data dass:
0 Select master page
-/Views/Shared/Site. Master QAdd Cancel I
Figure 14. Tạo view DanhMucLoaiSanPham trong folder SanPham
Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs"Inherits="BanHang.Views.SanPham.Index" %><asp:Content ID="viewIndex" ContentPlaceHolderID="MainContent" runat="server">
<hl>Đâỵ la'trang chinh cuã san phâm</hl>< /a sp :C o n te n t>
DanhMucLoaiSanPham.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true"
CodeBehind="DanhMucLoaiSanPham.aspx.cs"Inherits="BanHang-Views.SanPham.DanhMucLoaiSanPham" %>
<asp: Content ID="viewDanhMucLoaiSanPham" ContentPlaceHolderID="MainContent" runat="server">
<hl>Đây la'danh muç loaị san phârà</hl>
<% foreach (var lsp in ViewData.Model){ %><li>
<%= Html.ActionLink(lsp.TenLoaiSanPham, "DanhSachSanPham/" + lsp.TenLoaiSanPham, "SanPham") %>
</li><% } %>
</asp:Content>
DanhSachSanPham.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="DanhSachSanPham.aspx.cs" Inherits="BanHang.Views.SanPham.DanhSachSanPham" %><asp:Content ID="viewDanhSachSanPham" ContentPlaceHolderID="MainContent" runat="server">
<hl>Đây la'danh sach san phâm co'trong chuyên muọ</hl></asp:Content>
ChiTietSanPham.aspx
Microsoft Vietnam -D P E Team IBài số 3: Tổng quan về ASP.NET MVC Framework 17
![Page 18: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/18.jpg)
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="ChiTietSanPham.aspx.cs"Inherits="BanHang.Views.SanPham.ChiTietSanPham" %><asp: Content ID="viewChiTietSanPham" ContentPlaceHolderID="MainContent" runat="server">
<hl>Đâỵ la'Chi tiêt San phâm</hl></asp:Content>
2.6 Tìm hiểu về Models
Một model trong ứng dụng ASP.NET MVC chứa tất cả các nghiệp vụ logic mà không có trong controllers và views. Models chứa tất cả các tầng truy xuất dừ liệu logic và tầng nghiệp vụ logic. Ví dụ, nếu sử dụng LINQ to SQL để truy nhập dừ liệu thì phải tạo LINQ to SQL class ( file định dạng dbml) trong folder Models.
Mô hình dừ liệu LINQ to SQL ( Figure 15 )
Solution Explorer - Solution 'BanHang' (2 projects) ▼ -B X
ã I u? m I m m *Solution 'BanHang' (2 projects)
Ẻ BanHangẸ câl Properties É ^ References (±1 uQ App_Data Ệ □ Content Ẹ Conừollers
:*v) AccountController. cs c*y HomeContoiler.cs
SanPhamConfroller.es s 1̂ 5 Models
Ồ^ DataClasses.es ^ DataClasses.dbml.layout
DataClasses. designer. csffl □ Scripts s Views
á AccountIB ChangePassword.aspxặ ifil ChangePasswordSuccess.aspxÈ £ll Login.aspxS3 Register.aspx
a HomeSI lH About, aspx SI iH Index.aspx
0 {¿¡I SanPhamIB Lfj ChiTietSanPham.aspxạ DanhMucLoaiSanPham. aspxẸ DanhSachSanPham.aspxS3 i n Index.aspX
Figure 15. Mô hình dữ liệu LINQ to SQL
Xây dựng Iđp trớ giúp cho việc thao tác vdi dữ liệu thông qua LINQ to SQL
DataClasses.es
using System;using System.Collections.Generic; using System.Linq;
namespace BanHang.Models
Microsoft Vietnam -D P E Team IBài số 3: Tổng quan về ASP.NET MVC Framework 18
![Page 19: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/19.jpg)
partial class DataClassesDataContext {
public < > LayCacLoaiSanPham()
return LoaiSanThams.ToList();
public < > LaySanPhamTuLoaiSanPham(string loaisanpham)
return SanPhams.Where(1 => 1.LoaiSanPhaml.Id == loaisanpham) .ToList ();
public LaySanPhamQualD(int id)
return SanPhams.Single(s => s.Id == id);
Với lớp trợ giúp có thế thao tác dề dàng hơn với CO' sở dữ liệu khi cần . Chăng hạn với lóp DataClasses.es ờ trên khi cần truy nhập để lấy thông tin về sản phẩm có mã Id , có thể viết như sau trong bất kỳ một code -behind nào của Views (ví dụ với view DanhMucLoaiSanPham.aspx.es trong folder Views):
BanHang - Microsoft V isual Studio
File Edit View Refactor Project Build Debug Tools Test Window Help
■ 3 ' ¿ A ' 3 A & A A * ) ' • - ► Debug * Any CPU
m % b . " & I 1 t d mStart Page DanhMucLoaiSanPham.aspx.cs DanhMud.oa.SanPham.aspx SanPhamController.es
Sgt;
BanHang. Views. SanPham. DanhMucLoaiSanPham V VPage_LoadO
Q using System;using System.Collections.Generic; using System.Linq; using System.Web; using System. Web .Mvc;
Lusing BanHang.Models;
□ namespace BanHang.Views.SanPham{
public partial class DanhMucLoaiSanPham : ViewPage <List<LoaiSanPiiam> > {
public void Page_Load()<
li3tLoaiSanPham.DataSource = ViewData.Model; listLoaiSanPham.DataBind () ;|
>}
>
Figure 16. Binding data vào trong ViewADanhMucLoaiSanPham.aspx.es
Khi đó ta phải sửa đổi lại file Views\DanhMucLoaiSanPham.aspx cho phù hợp với code trên
<%0 Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true"
CodeBehind="DanhMucLoaiSanPham.aspx.cs"Inherits="BanHang.Views.SanPham.DanhMucLoaiSanPham" %>
<asp: Content ID="viewDanhMucLoaiSanPham" ContentPlaceHolderID="MainContent" runat="server">
Microsoft Vietnam -D P E Team IBài sd 3: Tông quan vê ASP.NET MVC Framework 19
![Page 20: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/20.jpg)
Đâỵ la'danh muç loaị San phâm</hl><hl>
<asp:Listview ID="listLoaiSanPham" runat="server"><LayoutTemplate>
<ul><asp:PlaceHolder ID="itemPlaceHolder"
runat="server"X/asp: PlaceHolder></ul>
</LayoutTemplate>
<ItemTemplate><li>
<%= Html.ActionLink(Eval("TenLoaiSanPham"), "DanhSachSanPham/" + Eval("TenLoaiSanPham"), "SanPham") %>
</l±></ItemTemplate>
</asp:ListView></asp:Content>
Views chỉ chứa tất cả những gì hiển thị cho người dùng trên browser, Controllers chỉ chứa các logic mà trả về view nào cho người dùng hoặc hướng từ action này đến action khác. Còn lại tất cả đều được viết trong Models.
2.7 Cấu trúc Views\Shared\Site.Master
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BanHang.Views.Shared.Site" %>
<!DOCTYPE html PUBLIC "-//W3C//DTE XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtmll/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-l" /> <title><%= Html.Encode(ViewData["Title"]) %></title><link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body><div class="page">
<div id="header"><div id="title">
<hl>My Sample MVC Application</hl></div>
<div id="logindisplay"><% Html.RenderPartial("LoginUserControl") ; %>
</div>
<div id="menucontainer">
<ul id="menu"><li><%= Html.ActionLink("Home", "Index", "Home")%></li> <li><%= Html.ActionLink("SanPham", "Index", "SanPham")%></li> <li><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div></div>
<div id="main"><asp:ContentPlaceHolder ID="MainContent" runat="server" />
Microsoft Vietnam -D P E Team IBài số 3: Tỏng quan về ASP.NET MVC Framework 20
![Page 21: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/21.jpg)
<div id="footer">My Sample MVC Application Scopy; Copyright 2008
</div></div>
</div></body></html>
>3- O a n h m u ũ c lo a ũ i s a ũ n p h â ũ m - M o z il la F i re fo x --------------------------------------------------------------------------------------------------------------------------- :
0 e Edit View « sto ry Bookmarks Tools Help
ệQP c \AJ 1 ủ http://localhost:2430/SanPham/DanhMud.oaiSanPham ứ * |G|- TMVCFrameworkretui
\Jk Most Visited ^ Getting s tarted ầ L Latest Headknes
L_ ASP.NETMVCFr... ASP.ÆTMVCNo . 32BmldmgaSmple ... [p] ASP.NETMVCFt... [ i ] ASP.NET MVC Ft... 1_3 Developer Notes . ASP.NET MVC Fr. 1_J D anh m ụ .
[ L o g in ]
My Sample MVC Application
Figure ¡7. Ket quả chạy ứng dụng khi thêm SanPham vảo ứng dụng ASP.NETMVC
3 Câu hỏi ôn tập
Hỏi: Views của MVC có thể sử dụng AJAX, javascript không?Đáp: Được, về bản chat, view trong ASP.NET MVC Framework cũng là một trang .aspx như với mô hình WebForm vì thế có thể thực hiện các tác vụ tương tự. Vì thế việc sử dụng jQuery, ASP.NET AJAX, và javascript đều có thể thực hiện được.
Hỏi: Xây dựng ứng dụng với ASP.NET MVC Framework thì trang web sẽ chạy nhanh hơn so với xây dựng trên nền WebForm cũ?Đáp: Chưa hẳn là thế. Neu xây dựng trang web với nền tảng WebForm mà sử dụng ít các controls, usercontrols hoặc ít events thì giá trị ViewState và PostBack không lớn nên sự thực thi không hẳn đã chậm. Trang web xây dựng theo nền WebForm chỉ thực hiện chậm khi giá trị của ViewState là quá lớn.
Hỏi: Có phải thực hiện test và debug ừên ASP.NET MVC Framework dề dàng hơn so với nền tàng WebForm. Đáp: Đúng. Vì việc thực hiện test và debug trên ASP.NET MVC Framework chỉ phải thực hiện trên Controller nên dễ dàng kiểm soát hơn so với thực hiện test và debug trên WebForm.
Microsoft Vietnam -D P E Team IBài sổ 3: Tỏng quan về ASP.NET MVC Framework 21
![Page 22: Tổng quan về ASP.NET MVC Frameworkdulieu.tailieuhoctap.vn/books/cong-nghe-thong-tin/lap-trinh-ung-dung/aspnet_3_5_lesson...ứng: đầu vào của controller là các điều](https://reader030.fdocuments.net/reader030/viewer/2022040208/5e3062f772fa5d22c0152fc5/html5/thumbnails/22.jpg)
4 Tài liệu tham khảo
http://www.asp.neưhttp://weblogs.asp.netyscottgu/archive/2007/l 0/14/asp-net-mvc-framework.aspx
Microsoft Vietnam -D P E Team IBài sổ 3: Tỏng quan về ASP.NET MVC Framework 2 2