If you can't read please download the document
Upload
tran-xuan-toan
View
230
Download
1
Embed Size (px)
Citation preview
Trang 1
ASP.NET MVC M c l c
Ph n I.
1. L ch s n Web
2. i c a ASP.NET MVC
2.1 Gi i thi u ASP.NET truy n th ng
2.2 m ASP.NET truy n th ng
2.3 Gi i thi u ASP.NET MVC (model-view-controller)
2.3.1 Ngu n g c ASP.NET MVC
2.3.2 n c
2.3.3 C nh c a m t d
2.4 gi
2.5 MVC2
3.
3.1
3.1.1
3.1.2
3.2 Views
3.2.1
3.2.2 T o
3.2.2 S d
3.3 Models
3.3.1
3.3.2 T o Database
Trang 2
3.3.3 T o Data Model v i Microsoft Entity Framework
3.3.4 S d ng Linq to Sql trong ASP.NET MVC
1.5
1.6 View Master Page
1.a.1 View Master Page
1.a.2 User Control Page
3.7 HTML Helpers
1.a.1
1.a.2 n trong HTML Helpers
1.a.3 B ng trong HTML Helpers
3.8 Validation Form Data
1.a.1
1.a.2 Validation Helpers
1.a.3 Validating with the IDataErrorInfo Interface
1.a.4 Style Validation Message
3.9 Model Binders
1.a.1 Model Binders
1.a.2 Action Filters
1.10 Ch ng th c Users
1.11 S d ng Unit Test trong ASP.NET MVC
5. Tri n khai ng d ng ASP.NET MVC
6. p Ajax
7. S d ng jQuery trong ASP.NET MVC
8. K t h p gi a Ph n II:
ng module website th c nghi m: NHANLUCQUOCTE.EDU.VN
Trang 3
n Web
Th i gian S c m nh Y m
Jurassis CGI n (l a ch n duy
nh
Ch
server
Bronze age IDC (Microsoft Internet
database connector)
Ch ng
t
qu nh d ng.
1996 ASP (Active Server
Page)
M ch th i gian
th c
2002/ 2003 ASP.NET 1.0/1.1 - Giao ditr
- d ch
- khuyl i
ng.
- C n
- Chi m nhi u bandwidth.
-
-
2005 ASP.NET 2.0
2007 ASP.NET Ajax
2008 ASP.NET 3.5
t chu t n i m t web server v i m c
c l v k t qu ng.
2. i c a ASP.NET MVC
2.1 Gi i thi u ASP.NET truy n th ng:
- D n n .NET h tr
- n vi c gi c HTTP ( n ch
code HTML b ng vi
server (m ng k t
n i v ki
- c v
trong t c l p. Thay th t ng StateFull UI (t m d giao
di n Web ch c -th x y ra
t k giao di n Web.
Trang 4
2.2 m ASP.NET truy n th ng: khi ng d
ngh c s d ng trong th c t ra nh m sau:
- i l n
n m t kh ng d li u l c truy a client-server.
- ng c k t n i gi u khi n s ki n
tr c t .
- gi i h
ID
ph c t t b i JavaScript.
- C m nh n sai trong vi o code-
i trang: Trong th c t n vi c
: vi c qu ogic trong ng d ng c a h
d d li u) v i nhau. T t qu
v .
- ki m th : Khi l t k n thi t
k c a h , h c vi c ki m th s tr n ph n m m
hi p cho vi c ki m th t ng.
t s components chu n nh m gi m
sinh ra s ng code b n (b n c n vi
i Web 2.0/Ajax, h tr nhi n m i nh
n 3.5 v i m t s p m t s controls
m c t o ra database t
a trong Visual Studio 2010 ASP.NET 4.0 s
n ID c a HTML, nh m gi m r c r i v ID ph c
t c.
2.3 Gi i thi u ASP.NET MVC : n t m i
nh t c a Microsoft hi c thi t k t
ng m t ph n m m t t (ph n m m t n m m b n mu n t
d i - c thi t k
th b n ph n m ng
d c thi t k h tr trong vi c ki m th .
2.3.1 Ngu n g c ASP.NET MVC:
* ASP.NET MVC 1.0
- ch s
i. N n t t
trang gi c g
Trang 5
T
Model View Controller pattern.
- ASP.NET MVC l t hi
ngu n m MonoRail
- n g c th t s Microsoft
thrie (m t trong nh o ra
h i th o Alt.NET
-2007.
- Cu n ASP.NET MVC 1.0
i.
- u ki n c ng ng d ng ASP.NET MVC:
+ Microsoft.Net Framework 3.5 SP 1
+ Microsoft ASP.NET MVC
+ Visual Studio 2008 SP 1
2.3.2 n c ng d vi t t t
c a Model View n:
- Model: Model c a MVC ch a t t c a ng d : x
d li a trong view hay controller. Model ch a g ng d ng,
p v d li u. Model c a MVC ch p (
ng trong mi n ng d ng ).
- View: View c a MVC ch
- Controller: Controller c a MVC ch u khi n
( control-flow ).
u: i) *
L a ng d ng web d
- r thay th t n m
- d n d u
khi n ng d ng c
- H th nh tuy n m i m nh m
- H tr t -
t m tra l i c khi b t
code.
- H tr k t h p r t t t gi i l i thi t k giao di n.
- S d t nh a ASP.NET.
m c a ASP.NET MVC
- n s ki n
ASP.
- u hi u bi t v
- n c i th nh b ng.
2.3.3 C nh c a m t d c t o 1 project
m nh b
- Kh ng visual studio 2008, ch n File -> New -> Project ->
ASP.NET MVC
Web Application
Trang 7
Trang 6
o m i d
o b test d
- Sau khi d i t c t o s n
b
C nh 1 project ASP.NET MVC
c ng d ng c a ASP.NET MVC
- App_Data: ch li
ch a m d li u c c b .
- Content: ch a n
- Controllers: ch a p controller c a ASP.NET MVC
- Models: ch p model c a ASP.NET MVC
- Scripts: ch n ASP.NET
- Views: ch a ASP.NET MVC
- Sau khi ch y th cho k t qu
sau :
Trang 9
Trang 8
ng d ng m nh do visual t o ra
n ASP.NET
.Net Framework: h tr i ng d ng d ng
console.
ASP.NET t ph n c ng nh m h
tr ng d
th i v m
ng d c ch ng
ng m n.
2.4 a ASP.NET webform
Trang 10
* S t c a ASP.NET MVC v i ASP.NET 2.0
ASP.NET 2.0 ASP.NET MVC
Ki Ki
Ki d ng vi
Controllers, Models, Views
S d a
webform, t ki
controls do server qu
ki u khi n
b
Truy c p d li u S d ng h u h
ngh truy c p d li u trong
ng d ng.
Ph n l
class t p
ng.
Debug i th c
hi n t t c bao g p
truy c p d li u, s hi n th ,
u khi
s d
unit test ki
th c trong controller.
T i. T i ch m khi
u
n.
ph i qu
qu
trang.
i
javascript.
D
URL Address C a ch
d ng
s >
C a ch
m ch theo d ng
Controllers/Action/Id
2.5 ASP.NET MVC 2
Trang 11
- ASP.NET MVC 2 ch ch
tri visual studio 2010
ho c visual studio 2008 sp1.
c h tr b : Windows 7; Windows Server 2003; Windows
Server 2008; Windows Vista
- i trong asp.net MVC 2:
+ New Strongly Typed HTML Helpers: H tr di t lambda (lambda
:
expression) tham chi n m t m ng hay t p h
Trang 12
tr t s strongly-
i:
nh
li u action (GET, POST, c th c thi .
Trang 13
p s n trong ASP.NET MVC 2
+ Auto-Scaffold UI Helpers with template customization: You can ensure
more maintainability as you modify your applications using strongly-typed helpers such
as Html.TexBoxFor. The new templated helpers let you easily associate HTML elements
for edit and display with data types improving productivity.
+ Asynchronous Controllers support
+ Support for rendering sub-sections of a page/site using
Html.RederAction
+ Improved Visual Studio tooling support
ch ng d ng MVC.
+ Lots of new helper functions, utilities, and API enhancements
Trang 14
+ DataAnnotation Validation Support: k t n ASP.NET MVC 2,
ng s m qu i (rules)
ng d ng v i 4 lu
ng s
Trang 15
c 2: T o action Create()
+ c 3: T o trang View
Trang 16
i ch th c hi n b t
i nh
ng ki ation rules r t tuy t v i bao g m c vi c h tr
validation rules c n client. T t c nh
Ch y th t qu
+ c 4: Ch m tra k t qu
tham chi
Trang 17
t ,
ng validation rule cho thu n, ta ch c n k
th a t l p RegularExpressionAttribute
d
sung r t nhi i, n u
tham kh o t i website:
http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc.
2.6 ASP.NET MVC 3
- ASP.Net MVC 3 ch ch tri n khai
k ho i ASP.NET
h tr tham kh o t i website:
http://aspnet.codeplex.com/wikipage?title=Road %20Map&referringTitle=MVC.
3. ph
3.1
3.1.1
- m nh n vi c x ng d ng bao g m vi c
nh a ng d nh th c thi, nh n d li u t mi
n nh
http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvchttp://aspnet.codeplex.com/wikipage?title=Road%20Map&referringTitle=MVChttp://aspnet.codeplex.com/wikipage?title=Road%20Map&referringTitle=MVCTrang 18
c t o ra b i Visual
* T
x u c a user b
ng request t user
3.1.2
- m v
tr k t qu v t. M t co tr v m t view, m t file, ho
n m
v m t ActionResult. B khung ASP.NET
MVC bao g u tr v
ng b ng vi c g
Trang 19
c Ki u tr v
View() ViewResult: m t view c a ASP.NET MVC.
PartialView() PartialViewResult: m t ph n(fragment) c a ASP.NET MVC view.
Redirect() RedirectResult: chuy n controller action ho
Content() ContentResult: g i n t.
File() FileResult: m c t i xong
RedirectToRoute() RedirectToRouteResult: chuy ng ho n controller action
ho c URL s d nh tuy n (route )
RedirectToAction() Tr v m t RedirectToRouteResult
M t s :
v m t ViewResult
v m t RedirectResult
c. Tr v m t ContentResult
a. Tr v m t ViewResult
b. Tr v m t Redirect Result
Trang 20
v m t ContentResult
t qu ch y th code ContentResult
ng c
d. Tr v m t fileResult
v m t ContentResult
Trang 21
n bi t
li u, ho c bi t khi m t nh n request t Ajax
a. s d ng AcceptVerbs: Thu n m t action
h tr m t s
th
b. s d tri n khai m t action
v c c
- Khi controller c
- Khi m n
nh
khi th
Trang 22
c. s d
thu g i m n thu
gi c ng thu th a l p ActionMethodSelectorAttribute.
ng m t l
l c IsValidForRequest(). N u k t qu tr v c
:
action s u
Trang 23
3.13
*Ngo i l u khi n t i (handling unknown action):
Khi
m t
i 404 Resource Not Found HTTP. Tuy nhi x
3.2 Views 3.2.1 View trong ng d n
c a ng d ng tr v t trang HTML
website c t m i th
3.2.2 T o view d nh p chu t ph
l c HandleUnknownAction()
Trang 24
n Add View
controller action
d ng h p tho i View (View Dialog)
n c a m t view
- a t o ch a 2 tag ,
Trang 25
xu t hi n trong tag c n HTML, tag
th hai s xu t hi n trong tag c n HTML.
%>
3.2.2 S d
- n truy i gi
d c h tr b
b t k lo d
li u
-ViewData gi u t m c p thu
tr t k ki u d li
- Khi s d ng ViewData, u v ki u d li u mong
mu ch a b t k ki u d li li u cho ViewData, ViewData t
d ki u objects
- :
Trang 26
t qu c
N n s d ng view b t o m t strongly
n viewdata tri n khai m t thu
o ViewData trong controller
1
Trang 27
d ng strongly typed data trong view
3.3 Models
3.3.1
- Models ch a t t c p v
xu d li p l trong ng d a t t c
logic ng d ng, ngo i tr
3.3.2 T o Database: minh h c h n bi t
d li u bao g c sau:
- Nh p ph i chu c App_Data, ch n Add, ch n NewItem
ch t o strongly typed view
Trang 28
- Ch
ch n Add
- d li n c App_Data,
trong c a s Server Explorer, nh p ph i chu c Tables, ch n Add New Table, Table
g m 4 c t. C t
3.3.3 T o Data Model v i Microsoft Entity Framework
- Nh p ph i chu c Model trong c a s Solution Explorer,
ch n Add, New Item.
- Trong h p tho i Add New Item, trong Categories nh c Data,
trong Templates nh p ch n ADO.NET Entity Data Model, trong m
DataModelProducts.edmx
Trang 29
- c choose model contents ch n item Generate From
Database,
nh p Next
- c Choose your data connection, nh p products.mdf cho data
c thi t l t n i.
Trang 30
- c Your Database Object, ch n table
- Sau khi nh t qu
Trang 31
* Gi i thi d li u s d
class Product
a. Hi n th t t c m d li u:
- Nh p ph n Add
View
Trang 32
- T o strongly- n List, nh n
Trang 33
Add
b. Hi n th m t m u tin duy nh t
- Nh p ph i ch n add view cho action Details trong controller
- K t qu
- T o strongly- Content ch n List, nh n
Trang 34
Details
c. T o m i m u tin
- K t qu
- Nh p ph i ch n add view cho action Create trong controller
- T o strongly- n List, nh n
Trang 35
Create
d. Ch nh s a m u tin
- n ph m m i
- K t qu
Trang 36
- T o strongly- n List, nh n
Edit
- K t qu c khi ch nh s a
- Ch nh s n ph m
- Nh p ph i ch n add view cho action Edit trong controller
Trang 37
- K t qu sau khi ch nh s a
u tin
- T o strongly- n List, nh n
Delete
- Nh p ph i ch n add view cho action Delete trong controller
Trang 38
3.3.4 S d ng Linq to Sql trong ASP.NET MVC
- c Microsoft gi i thi
t ph n c c thi t k
gi m t i m t s ng l n code c n vi
d li ng trong vi c t
stored procedure cho m i lo n th
c ORM(Ob t b
d ng.
- K t qu
-
- K t qu
Trang 39
- d ng Linq to Sql r n, t
m b c(c a s do visual t o ra
d li d nh truy v
n l c th n
n t
i Submit vi t nh c tr l
s d li u.
- :
a. T d li Sqlserver Express 2005). Sau khi t o
d li u t
b. ng l ng v i cac column
trong b ng Products. Trong c a s Solution Explorer, nh p ph c Models ch n Add,
Trang 40
c. T o m c g
c
t o ra m ng c a newProduct.
d. n Sql ho n
d c th t l p C# (Product),
d li u b
m t s thu
- Update l
- Tham chi n System.Data.Linq
Trang 41
e. T o l k t n d
li u th t s c
f. Li n ph d li u
Trang 42
* B
c 2: th c hi
a. Li li
li n khi s d ng k thu t Microsoft Entity Framework khi
d li u
g. Ch y th c k t qu
Controller
c 1: kh i t ng k t n d li u
Trang 43
b. C p nh t d li i thao
- c SaveProduct(newProduct product)
i s n ph m
-
trong l
- Khi th c hi d li u ta th c hi :
- K t qu
Trang 44
- ng h n action Edit
ta b i
d. t s n ph m
- c DeleteProduct(newProduct
product) trong l
- K t qu :
- d ng trong action Delete c a controller CRUD
Trang 45
3.5
- t trang t ng d ng ASP.NET
c chuy n ti n m ng d th c hi
c ng d ng ASP.NET MVC
- T p tin Global.asax ch t
c Application_Start() ch c g i
m t l n duy nh t khi ng d ng ASP.NET l c c i
c RegisterRoutes()
- c s d c u
t c
trong ng d
- K t qu khi ch
- Khi t o m i m t ng d :
Trang 46
- i b ng vi c g ng th c
th p nh sau:
a route
+ URL: m
m route
+ Constraints: t c nh m gi i h
ro p nh t.
+ Namespaces: t m gi i h p nh m tim ra
p nh t.
-
th g n s h tr c
Defaults, Contraints, ho c namespace.
- Tham s u(pattern)
nh ng d
+ /Product/Insert/ 23
+ /Home/Index/ 1
+ /Do/Something/Useful
- p v i URL sau:
u url
m n, trong khi ta request url 4 ph n).
- M u URL {controller}/{action}/{id}, v i tham s
c bi
quy nh lo i cont c s d u khi n
request t c
controller s d response l u.
Trang 47
- N
controller ho c action,
c s d ng tham s c truy
- Theo m nh, tham s m
Home, tham s action
i r ng).
- : v i website http://www.mysite.com/product
tham s
ng cho url:
http://www.mysite.com, ho -25-
tham s
- S d n
c bi t
i vi c thi m c thi HTTP Post.
tr m t s
Authenticated, NotEqual, Catch-ALL contrainst.
: n th ng
n vi p nh t, thu c u t
B - p v
c th c hi n.
ki m tra t p.
http://www.mysite.com/producthttp://www.mysite.com/Trang 48
3.6 :
3.6.1 View Master Page: M c c
website.
a. T o m p cho t t
c c \Views\Shared, nh p ph i chu t ch n Add,
New Item. Trong danh m c web ch
b. T o view content page: sau khi t
th t o m t hay nhi u view content pages d
- T m
controller, nh n ph i chu t ch n Add View.
- K t qu c n :
Trang 49
- Ch ng cho view
c. Thi t l p master page t Controller: S thu n l i c
- K t qu :
Trang 50
l a ch ng t i th i gian ch y
, gi s sau minh
h a b l a ch i gian ch y.
-
d. ng nhau:
- c 2: Ch y th c k t qu sau
Trang 51
- c 1: T o master page 1
- c 2: T o trang master page 2, import master page 1
- c 3: t o view s d ng master page 2
Trang 52
e. Truy n d li n master page
- c 1: T o l cho t t c
controller
ch ng h c i view data ch trong l p controller (vi
nh
- c 4: ch y th c k t qu
Trang 53
- c 3: L y d li u trong view
- c 2: T o controller k th a t controller
Trang 54
3.6.2 User Control Page
a. T o view user control
- m t ph n c a view. M
control cho
i dung tr t n
c hi n th trong nhi ch
- Nh n ph i chu c \Views\ n
s d ng
n Add, View
- c 4: K t qu c
Trang 55
- Sau khi t o xong m s d
trong view
b v
chu d ng script
- Gi s items m :
Trang 56
b. Truy n d li u t n ViewUserControl
- t qu
- i n i
Trang 57
c. s d t template
- c 1: T o m t controller m i (L y v m u tin trong
d li u)
- c 2: T o m hi n th
- c 2: K t qu c
Trang 58
- c 4: k t qu c
c 3: T o m tr v m
Trang 59
3.7 HTML Helpers
3.7.1
- l i n i dung HTML, ph n l
ch c tr v m t chu ng ng d
ri n Web d
c code HTML.
3.7.2 n trong HTML Helpers
- n m
n m t action controller.
c g
tham s
n
+ routeValues: t c truy n action
n
Trang 60
+ htmlAttributes: t thu
+ protocol: giao th : HTTPs )
link t i m t th div
trong view v news, ta s ch nh news cho fragment
- t o ra link d :
-
CheckBox(), DropDownList(), EndForm(), Hidden(), ListBox(), Password(), RadioButton(),
TextArea(), TextBox().
Trang 61
- m t form d ng HTML cho view.
Theo m nh, Html.BeginForm() s tr v m t form d ng post
back t u mu vi
tham s c
+ routeValues: t c truy n t i action
n post t i
n post t i.
r
c GET, b s d
+ htmlAttributes: t
- m t t u tin tro
d li u v d ng tag c a HTML.
:
d ng trong View
+ ng m n t cho dropdownlist
Trang 62
3.7.3 B ng trong HTML Helpers
- ASP.NET MVC ch h tr m t s n b sung
t s helper m i. Th tr i helpers, gi
c helper b n v a m i t o,
c hi n
c ti view c n s d ng helper b n v a m i
t o
+ c 3: K t qu
1 c nutSubmit() c l p Helpers
+
Trang 63
Gi s Ta
c k t qu
ng m t s helpers h
1. TagBuilder p r t h s
d ng c sau:
t l p m n 1 tag
+ GenerateId()- n 1 tag
+ MergeAttribute()-
nhi
+ SetInnerText()- t l p inner text c
ch nh r t ng, tag b u, tag k
p TagBuilder ng sau:
t t c a tag
c s d ng b i
c GenerateId()
n a tag, vi n
Trang 64
thu c i HTML.
a tag
:
ng m c helper t t
d ng trong View
2. S d ng l p HtmlTextWriter: thay th
+ c 3: k t qu c
Trang 65
cho l ng t s c bi
vi ng chu i HTML.
c
RenderBeginTag() c g i, thu
c
c g i, thu
vi c m tag HTML
c m v i RenderBeginTag ().
+ Write(): vi n lu ng xu t d li u(output stream).
+ WriteLine(): vi t m n lu ng xu t d li u.
:
c 2: Kh i t o d li u
d ng trong View
+ )
Trang 66
t, v i kh t t o
helpers h ng h p c th .
3.8 Validation Form Data: Validation form data m tra xem li u
li
l i h p l (validation errors) c a form b i thu t ng model state dictionary.
3.8.1 , b t cu n t n,
ch a m t t u (Model state), nh m bi u di n tr c
bi n l i h p l t c l i, b ng vi c truy n
tr ng u (model state dictionary). C hai l
u ch a thu n khai t n tr u
(exposes the model state dictionary).
3.8.2 Validation Helpers: t trong s n c s d
hi p l
m tra l i trong action testModelState trong
controller Home.
+ c 4: K t qu
Trang 67
c 3: nh p th d li m tra k t qu
+ p li u.
Trang 68
y r ng, l i h p l i
p nh n 2 tham s
l i. N u b t k l v false,
c l
3.8.3 Validating with the IDataErrorInfo Interface
hai do ASP.NET MVC h tr trong vi n Web ki p
l
public interface IDataErrorInfo {
// Properties string
Error { get ; } string this [ string columnName] { get ; }
}
c 1: k th a interface IdataErrorInfo
Trang 69
d ng trong action testModelState trong home
* Styling validation Error message tr t
s style css nh
controller
+ c 3: Ch y th c k t qu :
li p l
Trang 70
+ field-validatioin- n l b i
Html.ValidationMessage()
+ input-validation- b i
Html.TextBox() ho c Html.TextArea().
+ validation-summary-e ng cho c c
b i Html.ValidationSummary().
3.9
3.9.1 Model Binders: M m t request t
ng.
- t view ch ng m n cho vi c
t o
m i m t s n ph m sau:
-
n
i:
Trang 71
- th y, action controller ch p nh n tham s Product.
Model binder c t ng m i cho l p
u khi n vi c n
a l p Product
- ASP.NET MVC cung c
+ Model binder m nh (default model binder )
+ Form collection model binder
+ HTTP posted file d
model binder)
a. S d ng Model Binder default: model binder m t
t m t request c a browser, bao g
c datetime.
c Customer (nh ng class t ng
)
+ M
+ T p h
+ T
Tvalue>
*S d a Bind
- ta co th s d i v
nh n m
i b
i d u ph y ra kh i binding.
c
u ph y trong binding.
t giao m t tham s v i m t ti n t
c a 1 field trong form.
* ng d ng thu khi ta
d li n bind m ng
Trang 72
- N n exclude ProductID t c,
exclude ProductID ngay trong l
- n b sung
b. s d ng Form Collection Model Binder: t s thay th cho model
binder m s d truy t
m t t ng
c nh ki u.
: Trong action Create() ch p nh n tham s t form collection.
i v i thu
thu a
Trang 73
ng
form t ng myProduct c a l c UpdateModel() h tr m t s tham
s sau:
n vi c binding
+ prefix: ch a form v i ti n t c
bound v i model
+ includeProperties: m t m
binding
+ excludeProperties: m t m c lo i tr khi
binding.
+ valueProvider: ngu c s d ng trong su
n truy n tham s
th c UpdateModel(), m n truy n tham s c
c. S d ng HTTP Posted file d
k t h a form v ng c a class Product
UpdateModel() v c.
Trang 74
3.9.2 Action Filters
- M ta th c thi code trong m t s
hu ng sau:
c khi m c th c thi
+ Ngay sau khi m c th c thi +
c khi m t k t qu c th c thi +
Ngay sau khi m t k t qu c th c thi.
- M t thu ng cho m t
controller action ho
u s d ng action filters.
- ng m t action ki n action,
t ra c a s output c a Visual Studio.
ng l p LogAttribute k th a t l p ActionFilterAttribute
OnActionExecuting, OnActionExecuted,
n m t controller action.
Trang 75
3.10 Ch ng th c Users
a. T o users
- Ch ng th c s d p
OnResultExecuted, OnResultExecuting
+ d ng trong Controller
+ c 3: Ch y ch t qu :
Trang 76
l m truy c nh
administration tool, th
c a s Visual Studio, ch n ch n Asp.net
configuration t m c project. Sau khi website Administration tool kh
th t o m c ch ng d ng c
t 1 l n, n xu t hi n l
d ng Account Controller: N n t o users
s d c
o ng d ng MVC.
+ T o ng d ng MVC m i, ch
+ Nh
+ Nh
Trang 77
t o user m i.
b. Ch ng th c users: N mu n nh th
n truy c d ng thu c
h tr s n trong ng d ch ng th ng action controller ho c
c hi n ch ng th t c
y, ch c quy n Delete S n ph m. N u
mu c u ph
ng h n n
c. Ch ng th c user b gi i h n m
mu n ch ng th c ch i v i m t s
Trang 78
m d s d
, ta v t nh o ra
m
hi n th
3.11 S d ng Unit Test trong ASP.NET MVC
- Khi t o ng d ng ASP.NET MVC m i, Visual nh c nh
m t o ng d
Trang 79
- t o 1 kh i test m i
1. Nh p ph i chu c Controller, ch n Add, New Test.
2. Trong h p tho i Add New Test chon UnitTest.
3. Nh i Test c
4. Ch
1. Nh p ph i chu c controller, ch n add, class.
2. Trong h p tho
ch
- K t qu sau khi t o kh i test m i
Trang 80
3. class tr
* Hi a Test
1. u m t l t l p ch c test
2. u m c test
3. u m c ch y ngay l p t c
c m c test.
- t kh u k i m t
assertion. Khung test do Visual Studio Unit Test t o ra bao g m ba lo i l
b s d th c hi
+ Assert: l c th c thi assertions
+ CollectionAssert: l c bi t
cho t ng.
4 c p m i t o
Trang 81
+ StringAssert: l c assertion cho chu i
- Trong ph n l ng h d ng l p
Assert.Are th t s
d ng
n m c bi u c th
- N c v s
d ng l p
CollectionAssert, m tra xem hai t p h p
m tra
xem hai t p h n thi t gi .
- Cu nh v
chu m tra xem m t chu i
a chu c bi
m tra xem m t chu p v i m u bi t qui t c c th
- Visual Studio cung c n cho vi c
ch
+ Ch y test ch ng c nh hi n t i
+ Ch y t t c
+ Debug test ch ng c nh hi n t i
+ Debug t t c c test trong Solution
- Ng c nh b ng v chu
d , n
nh a ch n test b
th y test.
- Ch y test ch n thi t
l m nh n cho
vi c test.
:
T i v : Gi s m
n tham s
action Index()
Trang 82
V i m ng kh
Trang 83
5. Tri n khai ng d ng ASP.NET MVC
- Tri n khai ng d t ng d
c truy xu t b
- u t c n thi t cho vi c tri
n 5.1 tr
n 3.5
5.1
- n category Programs (Unistall a program) (Ch
Category), xu t hi
- Xu t hi n h p tho i
Trang 84
- Ch n ok.
- Sau khi ch i ch n m c
Administrative Tools
- Nh c IIS ta th y xu t hi n i
Trang 85
- c k t qu sau:
5.2 ng d ng web asp.net MVC
a. Tri visual studio
- Nh p ph i chu project, ch n property
Trang 86
- Sau khi ch n xong, nh
- K t qu sau khi visual studio th c hi
- Xu t hi n c a s thu i
Trang 87
b. Tri
- i
Trang 88
- Nh i
- Sau khi nh p ph c v a m i t
ch n Convert to Application.
- Cu p ph i chu ng d ng c k t
qu
Trang 89
6.
6.1
Asynchronous JavaScript and XML
thu t ng.
ng b b i s i m t s ng nh c a
d li u v c l y t upadate m t ph n trang
n load l i trang.
ng d ng s d ng ajax: Google Maps, Gmail, Youtube, and Facebook tabs.
6.2 Ajax ho
Trang 90
6.3 Ajax s d ng k t h p c a
- H u h u h tr
d ng ActiveXObject)
- d server.
- t t b n s dung do n code
sau
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlht tp.send(null);
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",url,false);
// Do not send null for ActiveX
xmlhttp.send();
}
document.getElementById('test').inn erHTML=xmlhttp.responseT
ext;
}
b. c s d hi n th li u.
c. ng s d nh d truy n d li u.
Trang 91
6.4 Send an AJAX request to a Server
g n server, b n s d send() c i
ng XMLHttpRequest.
Method Description
Open(method,url,async) Ch ra ki u c ra request s d ng b t
ng b
u c a POST, GET.
URL : v
ng b
Send(string) n server
String: ch s d ng cho POST request.
Vd:
a. GET.
xmlhttp.open("GET","demo_get.asp",true)
; xmlhttp.send(); n u b n mu n send data cho
server.
xmlhttp.open("GET","demo_get2.asp?
fname=Henry& lname=Ford",true);
xmlhttp.send();
b. POST
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
n u b n mu n send data cho server.
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.send("fname=Henry&lname=Ford");
6.5 Update Page With the Response From the Server
- l y n i dung tr l i t server, b n s d ng thu c
responseXml c a XMLHttpRequest.
Trang 92
Property Description
responseText L y d li u tr l i t i
responseXML L y d li u tr l i t
Vd:
a. N u d li u tr l i t n s d ng thu
responseText.
document.getElementById('test').innerHTML=xmlhttp.responseText
;
b. N u d li u tr l n mu n
xmlDoc=xmlhttp.responseXML;
var txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i
Trang 93
ReadyState Ch ng tr a XMLHttpRequest
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
Status 200: Ok
400: Page not found
b. AJAX - Creating a Callback Function
- T o ra m ki m tra n u k t qu tra l i s
function loadXMLDoc(url)
{
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(); // set
the callback function
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// set t he callback function
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
- a
XMLHttpRequest
-
function s tateChange()
{
if (xmlhttp.readyState == 4)
Trang 94
{
if (xmlhttp.status == 200)
{
// process whatever has been sent back here
document.getElementById('test').innerHTML=xmlhttp.responseT
ext;
}
else
{
alert("There was a problem in the returned data"); }
}
}
vd:
< html > <
head >
< script type="text/javascript" >
var xmlhttp;
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
func
tion
stat
eCha
nge(
)
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
Trang 95
// process whatever has been sent back here
document.getElementById('test').innerHTML=xmlhttp .responseT
ext;
}
else
{
alert("There was a problem in the returned data");
}
}
}
< /script >
< /head >
< body >
< div id="test" >
< h2>Let AJAX change this text <
/div >
Click Me Click Me
< /body > <
/html >
* AJAX AND CLIENT SCRIPT
a. d ng javascript tool kit
- gi m b t s
s d ng toolkit c a m
p m t l m v ph bi n
- Vd c p nh t m t ph n c n ph trang
- Trong s t nh
Miscrosoft s n sau
- M t k p v ng n d ng
ng h
ng d ng webforms truy n th ng v i h u h n javascript c a hang th 3.
- n t th b
s d ng b
Trang 96
b.
* Mvc cung c p m d th c hi n vi c c p nh t
m t ph n trang v i s b ng b
a. Ajax.ActionLink() s t
Khi b n n dung m
n t i
b. Ajax.BeginForm() s t
Khi b i dung m
t n t i
c.
d.
* Fetching Page Content Asynchronously Using Ajax.ActionLink
c khi b s d ng n ph i tham chi n 2 file
javascript
- Ch ra ajax.* helper
- n ASP.NET AJAX
M a trong folder /script c a b t c m t project ASP.NET
MVC
n c n c n head c a trang view ho c master
page Vd:
< html >
< head runat="server" >
S l a ch n c a b c th hi n .
Trang 97
< /head >
< /html >
Vd < h2>What time is
it?
< p > Show me the time in: < %= Ajax.ActionLink("UTC",
"GetTime", new { zone = "utc" }, new AjaxOptions {
UpdateTargetId = "myResults" }) %> < %=
Ajax.ActionLink("BST", "GetTime", new { zone = "bst" }, new
AjaxOptions { UpdateTargetId = "myResults" }) %> < %=
Ajax.ActionLink("MDT", "GetTime", new { zone = "mdt" }, new
AjaxOptions { UpdateTargetId = "myResults" }) %> < /p >
Results will appear here
< /div > < p >
This page was generated at (UTC)
< /p >
-V i m i link s request d li u t action method g
i s y s l y d li u response t
thay th n i dung c a th
-N u b ki n gi x t s request b t
ng b on method g server s tr l i l i
Trang 98
p s c hi n th n phai t o ra m t
public string GetTime(string zone) { DateTime time =
DateTime.UtcNow.AddHours(of fsets[zone]);
return string.Format("The time in {0} is {1:h:MM:ss
tt}", zone.ToUpper(), time); }
private Dictionary offsets = new
Dictionary { { "utc", 0 }, {
"bst", 1 }, { "mdt", - 6 }
} ;
- Ch c bi n bi
b ng b ng.
Trang 99
Trang
100
c. Passing Options to Ajax.ActionLink
- u h t ch ng v i m
html.ActionLink
Trang
101
- a Ajax.ActionLink ()
Thuoc tinh Kieu du lieu Mo t
Confirm string N u ch n, request
b ng b ch c th c hi n khi user nh n ok
httpmethod string Ch ra method c a resquest b ng b
gi i h s d ng nh ng
a http vd Put ho c Delete
InsertionMode insertionMode(enum) Li n i dung c
i dung m i t
ph n t (insertBefore) ho c i(insertAfter)
LoadingElementid String N u ch ra id c a ph n t html s c hi n th
OnBegin String c g c khi request b t
ng b b u, b h y request b ng b b i
l i false
OnComplete string ng b
t ch
OnSucess String c g i khi request b ng b
i s ki
ki n OnComplete
OnFailure String i khi request b t
b i s ki c g i sau s
OnComplete
UpdateTargelid String Ch ra id c i dung t c
url String
d. Running JavaScript Functions Before or After Asynchronous Requests
Trang
102
- B n s d t
ng b . Th t ->OnComplete->OnSuccess ho c OnFailure. B h y b
chu l i false t
-Khi b t c a b c g nh n m i s m i th v i s
ki
- hi n th l i khi request b l i, b
< script type="text/javascript" > function
handleError(ajaxContext) { var response =
ajaxContext.get_response(); var statusC ode =
response.get_statusCode();
alert("Sorry, the request failed with status code " +
statusCode);
}
< /script > < %= Ajax.ActionLink("Click
me", "MyAction",
new AjaxOptions { UpdateTargetId = "myElement", OnFailure =
"handleError"}) %>
i s
get_loadingElement(), get_Request(), get_Response(), get_updateTarget(). Nh c
n s d nh a ng n t i
Ki u tr l i
get_data() L html tr l i t server( n u request
String
get_insertionMode() L a ch n insert default, top,sau. 0 ,1, 2
get_loadingElement() loadingElementid Dom element
get_request Xu t ra request asp.net ajax
get_response() L y response c a server
get_updateTarget() Th c p nh t n i dung Dom element
e. Detecting Asynchronous Requests
Trang
103
-B l y n i dung html t b n ko c n bi t ho c lo l
d ch v request b ng b
-D nh request b i l n MicrosoftMvcAjax.js t o ra m t
request b ng b i s t bi c g -Requested-With v
- c IsAjaxRequest() trong
HttpRequestBase. - Vd public ActionResult GetTime(string zone) { DateTime
time = DateTime.UtcNow.AddHours(offsets[zone]);
if(Request.IsAjaxRequest()) {
// Produce a fragment of HTML
string fragment = string.Format("The time in {0}
is {1:h:MM:ss tt}", zone.ToUpper(), time);
return Content(fragment); } else { // Produce a
complete HTML page
return View(time);
}
}
f. Submitting Forms Asynchronously Using Ajax.BeginForm
- n mu n bao g m d li , cho
p n y b s d
n 12.1
- Vd: b c p nh c v
< h2>What time is it? < %
using(Ajax.BeginForm("GetTime", new AjaxOptions {
UpdateTargetId = "myResults" })) { %> < p > Show me
the time in:
< select name="zone" >
< option value="utc">UTC
Trang
104
< option value="bst">BS T <
option value="mdt">MDT
< /select > < input type="submit"
value="Go" / >
< /p >
< % } % >
< div id="myResults" style="border: 2px dotted red; padding:
. 5 em;" > Results will appear here
< /div >
< p >
This page was generated at (UTC) < /p >
- V i action method GetTime ()
B t qu
g. Invoking JavaScript Commands from an Action Method
Trang
105
- u tr v c a action
n tr l i m nh javascrip t action method.
- cho b u n ng s th
l nh javascript c a b u d ng khi b n th c hi n
m ng n c p d server.
Vd:
< h2>List of items
< div id="message">
< ul >
< % foreach (var item in Model) { % >
< li id="item_" >
< b>
< /li >
< % } % > Page generated at
- t o ra m t request b ng b i
y u c u model layer
n mu n client c p nhat l i DOM. B
Trang
106
[AcceptVerbs(HttpVerbs.Post) ] // Only allow POSTs (this action
causes changes) public JavaScriptResult DeleteItem(int itemID)
{ var itemToDelete = GetItem(itemID);
// TODO: Actually instruct the model layer to delete
"itemToDelete" // Now tell the browser to update its
DOM to match var script =
string.Format("OnItemDeleted({0}, {1})",
itemToDelete.ItemID,
JavaScriptEncode(itemToDelete.Name)); return
JavaScript(script); } private static string
JavaScriptEncode(string str)
{ // Encode certain characters, or the JavaScript expression could
be invalid return new JavaScriptSerializer().Serialize(str); }
client b n t
< script type="text/javascript" >
function OnItemDeleted(id, name)
{
document.getElementById("message").innerHTML = name + " was
deleted "; var deletedNode = document.getElementById("item_"
+ id); deletedNode.parentNode.removeChild(deletedNode); }
< /script >
Trang
107
7. S d ng jQuery trong ASP.NET MVC
7.1 Referencing jQuery
V i m n jquery trong folder /Script.
Gi s d n c n tham
chi
Vd: b n code n do n the head < head runat="server" > < script src=""
type="text/javascript">
< /head >
7.2 Basic jQuery Theory
ng c s d query t t c
i v i css. Vd:
t c th div trong trang c a b d ng class css
tr l i object c a javascript. H u h t jQuery API g m m t t p h p c a
m cho t t c
n m t. Cho ti n l jQuery cung c p m t c n g
Vd:
t c t t c <
c ch a trong th
Trang
108
t t t hi n th ph n t v i id c n
th c l
a tat c c disable
t c th
option, thay th color c i opactiy v 0.
t s n g n. N d ng jQuery thi b n ph i vi t r t
nhi u code c tr css 3 cho selector b t ch t
tr
7.3 Waiting for the DOM
-H u h t s c
n, b u b t code
u c a b n s ko ngay l p
t cu i trang, vi v n c a b n
-Truy n th ng, nh n s gi i quy t v n y b i t o code c a
b n d ki n onload c y code c a ban ch s run khi trang
ng h n ch .
Th ch b k t h p
nhi c l p v i nhau.
Onload handler ph i ch cho t t c c load, g
v m trang c a b n
-Gi i quy t v n y t t bi a b n s m nh t
n l
< script >
$(function() { // Insert your
initialization code here
}) ;
< /script >
Trang
109
- B n truy th c hi n s m nh t khi
ng
m y t i v t
t t c nh ng jQuery c a b
7.4. Event Handling
- i quy t v v t. Jquery cung
c p m t m t l
$("img").click(function() { $(this).fadeOut() })
Khi b c g i
7.5. Global Helpers
- jQuery cung c p m c
vi c v i nhi
- Vd: m
method Description
$.browser Cho b n bi c s d ng. B n s y m t c a nh ng
nh c k t qu
$.browser.mozilla, $.browser.safari, $.browser.opera.
$.browser.version Cho b n bi t version c t dang s d ng
$.support nh li tr m
$.strim(str) Tr l i chu i str v n tr ng cu i
$inArray(val,arr) Tr l i v a val trong mang arr. jQuery cung c y b
Trang 110 110
- p h y c
cung c p h th t s .
7.5. Adding Client-Side Interactivity to an MVC View
- Gi s b public class
MountainInfo { public st ring Name { get; set; } public int
HeightInMeters { get; set; } }
- B n s t p h < h2>The Seven Summits
< div id="summits" >
< table >
< thead> < td>Item Height (m)
Actions
< /tr> < % foreach(var
mountain in Model) { % >
< tr >
< td> <
td>
< td >
< % using(Html.BeginForm("DeleteItem", "Home")) { % >
< %= Html.Hidden("item", mountain.Name) % > <
input type="submit" value="Delete" / >
< % } % >
< /td >
< /tr >
Trang 111 111
< % } % >
< /table >
< /div >
- t v n th c thi t c g
- DeleteItem() action method se hi n th :
- th c hi ng s d i m c
k t h p v t o ra HTTP POST v ng URL
v c delete.
Trang 112 112
B y gi ch ng ta s
7.6. Improvement 1: Zebra-Striping
- c ph bi n c a thi t k
nhau.
- n l a ch b sung
< % int i = 0; % >
< % foreach(var mountain in Model) { % > < tr
>
-
< script type="text/javascript" > $(function() { $("#summits tr:nth - child(even)").css("background - color", "silver"); }); < /script >
7.7 Improvement 2: Confirm Before Deletion
- c khi b n th c hi phuc h i l t nh t b
c t c c khi b n th c hi n c n c nh
n ph i add s ki
n s dung jquery nhu sau
Trang 113 113
- B n add kh a trang $("#summits form[action$='/DeleteItem']").submit(function()
{ var itemText = $("input[name='item']",
this).val(); return confirm("Are you sure you want
to delete '" + itemText + "'?"); });
7. 8 Improvement 3: Hiding and Showing Sections of the Page
-M t ph bi n m n nh a trang cho t i khi
b n bi t ch t ch i s d ng.
-Vd: b n mu n c t certain trong grid thi n ho c hi
v t v cho m t ki ng n u b u b n
client b n s ph i ch y.
- b qua v n. b n b sung code
vao ph n c a trang.
$("Show heights") .insertBefore("#summits") .children("input").click(function() { $("#summits td:nth - child(2)").toggle(); }) .click();
Trang 114 114
7.9 Client/Server Data Transfer with JSON
- ng b c n truy n d li cho client. B i
ng, m ng, ho nh d
- tr n d li tr cho vi c
nh n JSON.
- Action method tr l i JSON.
public class StockData { public decimal
OpeningPrice { get; set; } public decimal
ClosingPrice { get; set; }
public string Rating { get; set; }
} public class StocksController :
Controller {
public JsonResult GetQuote(string symbol)
{
// You could fetch some real data here if(symbol == "GOOG") return new JsonResult {
Data = new StockData {
Trang 115 115
OpeningPrice = 556.94M, ClosingPrice = 558.20M, Ratin g
= "A+"
}} ;
else
return null;
}
}
- client b l c chu i JSON s d
ng javascript b i g tr
v
< h2>Stocks < % using(Html.BeginForm("GetQuote",
"Stocks")) { %> Symbol :
< %= Html.TextBox("symbol") % > <
input type="submit" / >
< % } % >
< table >
< tr>Opening price:
< tr>C losing price: <
tr>Rating:
< /table >
This page generated at
- hi n th a Stock $("form[action$='GetQuote']").submit(function() {
Trang 116 116
$.getJSON($(this).attr("action"), $(this).serialize(),
function(stockData) {
$("#openingPrice").html(stockData.OpeningPrice);
$("#closingPrice").html(stockData.ClosingPrice)
; $("#stockRati ng").html(stockData.Rating); })
; return false;
7.10 Fetching XML Data Using jQuery
-N s d nh d nh d
n nh n d li
B n s a chon n
- n c n tr l i XML t action method.
- Vd: b i action method cho cho public ContentResult GetQuote(string symbol)
{
// Return some XML data as a string
}) ;