1. DEVELOP WEB APPLICATION
WITH ASP.NET MVC 3.0
By
Mr.Prakob Pongpatimet
(อ.ประกอบ พงศ์ปฏิเมธ)
CSPM, MCSD
Chief Software Architect
ThaiSoftwareFactory.com
Thailand
23 May 2554 – 3 June 2554
3. Instructor Backgroud
Prakob Pongpatimet has more than 20 year experiences
Solution
Application Lifecycle Management with Visual Studio and TFS 2010
Process Improvement
Research and Development Microsoft new technology.
Current Activities (July 2553- Present):
Microsoft Technical Consultant at Sripatum University
Technical specialist trainer on software development process an tools at
Microsoft Thailand.
Develop and train software development solution and software testing at
Kasertsat University.
Prepared by Prakob Pongpatimetc
3
4. Agenda Day 1
Module 1: Design Principles และ Patterns บน Software Factory
Toolkits
Module 2: Introduction to ASP.NET MVC Framework 3.0 -
4.0 และ Razor View Engine
5. Agenda Day2
Module 3: Design Application Architecture in MVC
Module 4: Understanding Controller and Action
Module 5: Understanding Model
Module 6: Implement Clinic Application
6. Agenda Day 3
Module 7: Introduction to MVC
Module 8: Introduction to ADO.NET Entity
Framework
Module 9: Understanding MVC Routing
Module 10: Develop Patient Information
Module 11: Presentation Layer and View
Module 12: View and HTML Helper
7. Agenda Day 4
Module 14: Master Page and User Control
Module 15: Paging Support
Module 16: Introduction to software testing and
Test Driven Development (TDD)
Module 17: Authorization and Authentication
Module 18: Working with Ajax and JQuery in MVC
Framework
8. Agenda Day 5
Module 19: Modeling User Requirement
Module 20: How to develop code from use case
and Architecture Model
9. MODULE 1: DESIGN PRINCIPLES
AND PATTERNS IN SOFTWARE
FACTORY TOOLKITS
Stylize, edit, and animate your media
9
10. What Is a Good Software ?
Good software :
Work as intended
Easy to change
In a large organization :
Easily to maintain
อ.ประกอบ พงศ์ปฏิเมธ
12. Software Design Principle
Making software easily to change:
Design component loosely coupled.
Reduce the dependencies
Focus on maintainability quality attribute
13. Cause of Poor Design
A poor design typically has two causes:
The architect’s insufficient skills,
Imprecise or contradictory requirement.
Contradict requirements usually result from bad
communication.
Solve this communication problem:
Apply agile methodologies
14. Which Food Do You Like?
From spaghetti code to lasagna code
Cohesion
Coupling
15. Separation of Concerns
Identifying the concerns
Modularity
Information hiding
SoC and programming
paradigms
19. MVC Patterns
MVC is a loosely defined pattern.
The primary goal of MVC is to split application
into distinct pieces.
Model: Application functionality
View: Graphical element
Controller: Action on the Model and select the next view.
อ.ประกอบ พงศ์ปฏิเมธ
20. The Microsoft ASP.NET MVC framework is Microsoft’s
newest framework for building web applications.
Designed to build good software easier.
Support pattern-based software development and unit
test
What is ASP.NET MVC?
อ.ประกอบ พงศ์ปฏิเมธ
21. What is MVC?
•A design pattern
•Acronym for Model ● View ● Controller
•Separation of concerns
อ.ประกอบ พงศ์ปฏิเมธ
22. ASP.NET MVC Is Part of the ASP.NET
Framework
.NET Framework
ASP.NET Framework
ASP.NET MVC ASP.NET Web Forms
อ.ประกอบ พงศ์ปฏิเมธ
23. Model: Contain application logic that is not
contains in View and Controller.
Validation Logic
Business Logic
Data Access Logic
View: Contain HTML markup and view logic
Controller: Contain control flow logic. An MVC
controller interacts with MVC models and views to
control the flow of application execution.
The Architecture of an ASP.NET MVC
Application
อ.ประกอบ พงศ์ปฏิเมธ
24. What is MVC?
Step 1
Incoming request directed to Controller
Request
Controller
อ.ประกอบ พงศ์ปฏิเมธ
25. What is MVC?
Step 2
Controller processes request and forms a data Model
Controller
Model
อ.ประกอบ พงศ์ปฏิเมธ
26. What is MVC?
Step 3
Model is passed to View
Controller
View
อ.ประกอบ พงศ์ปฏิเมธ
27. What is MVC?
Step 4
View transforms Model into appropriate output format
Controller
View
อ.ประกอบ พงศ์ปฏิเมธ
28. What is MVC?
Step 5
Response is rendered
Response
Controller
View
อ.ประกอบ พงศ์ปฏิเมธ
29. ประโยชน์ของ MVC
ง่ายต่อการทดสอบชิ้นงานของ User Interface
Separation of Concerns มีการแยกโค้ดของ
Presentation Layer ออกเป็นส่วน ๆ ตามลักษณะการทางานใน
รูปแบบ
Low coupling และ
High Cohesion
อ.ประกอบ พงศ์ปฏิเมธ
30. Lab 2: Create General Master Type และ General
Master Code
Create MVC 3.0 Project WebForm named
“FirstMvcApp”
Create ClinicDB
Create GMTypeController
Create View
Index
Create
Edit
Delete
40. ASP.NET MVC3.0
40
ASP.NET MVC 3 builds on ASP.NET MVC 1 and 2,
adding great features that both simplify your code
and allow deeper extensibility.
Razor View Engine
41. Razor View Engine
41
It is the result of code focused template approach.
Minimize the code, compact and very easy to learn.
we can use C#.NET or VB.NET and very quick and
productive and has built in intellisense support with
Visual Studio.
43. Razor View Engine Features
43
We can use @model syntax for specifying the type
being passed to the view
Master page like default for entire website such as
(layoutpage)
If you want to display the text without HTML-encoding,
use Html.Raw method
A new way to add comment like @* this is comment *@
Sharing code among multiple views is possible now
using _viewstart.cshtml for C# and _viewstart.vbhtml
file for VB.NET
46. Razor View Engine
Other popular ASP.NET MVC view engines used today
include Spark and NHaml.
Razor view-engine :
optimized HTML generation using a code-focused templating
approach.
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
46
47. Design Goal of Razor View Engine
Compact, Expressive, and Fluid
Easy to Learn
Is not a new language
Works with any Text Editor
Has great Intellisense
Unit Testable
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
47
52. If Block and Multi Line Statement
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
52
53. Integrating Content and Code
Razor’s language parser is clever enough in most cases to infer whether
a @ character within a template is being used for code or static content.
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
53
54. Layout/MasterPage Scenarios – The Basics
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
54
Razor also supports this
concept using “layout
pages”
55. Simple Layout Examples
It can contain any static HTML content we want to include in
it, as well as dynamic server code.
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
55
57. Layout/MasterPage Scenarios – Adding Section
Overrides
Supporting the ability
to define different
“sections”
layout can then
override and “fill-in”
with custom content.
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
57
58. Encapsulation and Re-Use with HTML Helpers
Code Based HTML Helpers
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
58
59. Encapsulation and Re-Use with HTML Helpers
Declarative HTML Helpers
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
59
You’ll be able to place .cshtml
files that contain these helpers
into a ViewsHelpers directory
and then re-use them from any
view or page in your site
60. Passing Inline Templates as Parameters
อ.ประกอบ พงศ์ปฏิเมธ
Prepared by Prakob Pongpatimet
60
These “inline templates” can contain both HTML and code, and can
be invoked on-demand by helper methods.
64. You will learn
64
How to create a new ASP.NET MVC project.
How to create ASP.NET MVC controllers and views.
How to create a new database using the Entity
Framework code-first paradigm.
How to retrieve and display data.
How to edit data and enable data validation.
65. 1. Creating Your First Application
65
Create Mvc3 Application named “MvcMovie”
Internet Application
Razor View
66. 2. Adding Controller
66
Add HelloWorldController
Create Two Action Methods
Execute the application
Pass Some Parameter Information From URL
69. Pass Some Parameter Information From
URL69
public string Welcome(string name, int numTimes = 1)
{ return HttpUtility.HtmlEncode("Hello " + name
+ ", NumTimes is: " + numTimes);
}
http://localhost:xxxx/HelloWorld/Welcome?name=
Prakob&numtimes=4
70. 3. Adding a View
70
Add Index View
Changing Views and Layout Pages
Passing Data from the Controller to the View
72. Changing Views and Layout Pages
72
Go to the /Views/Shared folder in Solution
Explorer and open the _Layout.cshtml file.
Update title to MVC Movie App
Run the application
Click About page
View Source Code
73. Change Title of the Index Page
73
http://localhost:xx/HelloWorld
74. Passing Data from the Controller to
the View74
Add a Message and NumTimes value to the
ViewBag object.
ViewBag is a dynamic object
ViewBag object has no defined properties until you
put something inside it.
75. Update Welcome Action
75
Now the ViewBag object contains data that will be
passed to the view automatically.
77. 3. Add a Model
77
The Entity Framework (often referred to as “EF”)
supports a development paradigm called code-first.
Code-first allows you to create model objects by
writing simple classes.
(These are also known as POCO classes, from
"plain-old CLR objects.")
82. The Error Message
82
This package (or one of its dependencies) contains
PowerShell scripts and needs to be installed from
the Packet Manager Console
Solution
open the package manager console (In Visual
Studio go to View->Other Windows->Package
Manager Console) and try this to install the old
EFCodeFirst
Install-Package EFCodeFirst
83. Adding Model Classes
83
Add Movie Class
Add MovieDBContext Class
The MovieDBContext class represents the Entity Framework
movie database context, which handles fetching, storing,
and updating Movie class instances in a database.
84. Accessing your Model's Data from a
Controller84
Create MovieController
Add Index View
Strongly-Type Model @model
Creating a Connection String and Working with
SQL Server Express
86. Strongly typed Models and the
@model keyword86
The ViewBag is a dynamic object, and provides a
convenient, late-bound, way to pass bits of information
to a view.
This strongly-typed approach enables richer editor
intellisense, and better compile-time checking of your
code.
We are passing an argument when calling the View()
helper method within our Index action
View templates can indicate the type of object they
expect to be passed using a @model statement at the
top of the view template file.
87. Creating a Connection String and
Working with SQL Server Express87
The MovieDBContext class we created in the
previous section handles the task of connecting to
the database and mapping Movie objects to
database records.
Add the following connection string to the
<connectionStrings> element in the Web.config file.
<add
name="MovieDBContext" connectionString="Server=.SQLEXPRESS;
Database=Movies;Trusted_Connection=true" providerName="
System.Data.SqlClient" />
88. Create Movie Database
88
When you first accessed the MovieDBContext
instance using the MoviesController code above, the
Entity Framework automatically created an empty
Movies database for you. It mapped the Movies
properties of the MovieDBContext class to a new
Movies table that it created in the database.
Each row in the table is mapped to a Movie
instance and each column in the Movies table is
mapped to a property on the Movie class.
89. 4. Adding a Create Method and Create View
89
implement the /Movies/Create URL
Add Create Form
Processing the HTTP-POST
Run Creating a Movie
92. 92
The ModelState.IsValid check in the code above
verifies that the data submitted in the form can be
used to create a Movie object .
If the data is valid, our code adds the posted Movie
to the Movies collection of the MoviesDBContext
instance.
94. 5. Adding a New Field to the Movie Model and Table
94
Adding a Rating Property to our Movie Model
public string Rating { get; set; }
Modify Index page
Modify Create page
Managing Model / Database Schema Differences
95. 95
By default, when you use EF code-first to
automatically create a database (like we did
earlier in this tutorial), EF code-first adds a table to
the database to help track whether the schema of
the database is in sync with the model classes it was
generated from.
96. Two Approaches to Resolve
96
Have the Entity Framework automatically drop and
re-create the database based on the new model
class schema.
Modify the schema of the existing database so that
it matches the model classes.
97. Automatically Recreate the Database
on Model Changes97
Let’s update our application so that EF code-first
automatically drops and re-creates our database
anytime we evolve the model of our application.
Warning:
You should only enable this approach of
automatically dropping and re-creating the database
using a development/test database, and never on a
production database with real data. Using it on a
production server can lead to data loss.
99. MovieIntializer
99
The MovieInitializer class above indicates that the
database used by our Model should be dropped
and automatically recreated if our Model classes
ever change.
We are using its “Seed” method to specify some
default data that we want to automatically add to
the database any time it is created (or re-created).
100. MovieIntializer
100
Now that we’ve defined our MovieInitializer class,
we’ll want to wire it up so that each time our
application runs it checks to see whether our Model
classes are different than the schema in our the
database, and if so re-creates it to match (and then
populates it with the sample seed data).
101. Open the Global.asax file
101
The Global.asax file contains the “Application
Class” of our project, and contains an
Application_Start() event handler that will run when
our application first starts up.
102. Let’s add two using statements to the
top of the file.102
using System.Data.Entity.Database;
using MvcMovie.Models;
The DbDatabase.SetInitializer statement we just added
indicates that the database used by our MovieDBContext
should be automatically deleted and recreated if the schema
in the database does not match the current state of our Movie
model objects.
It will then populate the database with the “seed” sample data
specified within our MovieInitializer class.
103. 103
The DbDatabase.SetInitializer statement we just
added indicates that the database used by our
MovieDBContext should be automatically deleted
and recreated if the schema in the database does
not match the current state of our Movie model
objects. It will then populate the database with the
“seed” sample data specified within our
MovieInitializer class.
105. Fixing the Precision of our Price
105
EF code-first created our database, it used a
default precision setting of (18:0) when creating
columns for Decimal data-types.
106. Update Movie Model
106
To change the precision of how our Price column is
persisted in a database, open up the Movie.cs file
within the Models folder of the project.
using System.Data.Entity.ModelConfiguration;
108. 6. Adding Validation to the Model
108
DRY (Don’t repeat Yourself)
You can declaratively specify validation rules in one
place (the model class) and then those rules are
enforced everywhere within the application.
109. Adding Validation Rules to the Movie Model
109
Open Movie Model
using System.ComponentModel.DataAnnotations;
111. 111
EF code-first ensures that the validation rules you
specify on a model class are enforced before
allowing the application to save changes in the
database.
113. How Validation Occurs in the Create
View and Create Action Method113
The second Create method calls ModelState.IsValid
to check whether the movie has any validation
errors.
If the object has validation errors, the Create
method redisplays the form. If there are no errors,
the method saves the new movie in the database.