mvc 3.0 ku day 1 v 1.1

Post on 08-Aug-2015

22 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

DEVELOP WEB APPLICATION WITH ASP.NET MVC 3.0

ByMr.Prakob Pongpatimet

(อ.ประกอบ พงศป์ฏิเมธ)

CSPM, MCSD

Chief Software ArchitectThaiSoftwareFactory.comThailand

23 May 2554 – 3 June 2554

วัตถุประสงค์ของหลักสูตร

เป็นการน าเสนอการออกแบบและพฒันาระบบงานระดบัเอนเตอร์ไพรซ์ ผา่นทางเคร่ืองมือ Visual Studio 2010

ASP.NET MVC Framework 3.0

ADO.NET Entity Framework

การน าเสนอ รูปแบบมาตรฐาน (สากล) ของการสร้างสถาปัตยกรรมซอฟต์แวร์ ให้แก่กลุม่นกัพฒันา

น า Software Factory Solution มาปรับปรุงให้เกิดมาตรฐานการพฒันา

ขยายขอบเขตการใช้งานออกไปยงับริษัทเอกชน และมหาวิทยาลยั ต่าง ๆ

แลกเปลี่ยนเทคโนโลยี ชิน้สว่นซอฟต์แวร์มาตรฐาน ในระหวา่งกลุม่นกัพฒันา

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

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

Agenda Day2

Module 3: Design Application Architecture in MVC

Module 4: Understanding Controller and Action

Module 5: Understanding Model

Module 6: Implement Clinic Application

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

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

Agenda Day 5

Module 19: Modeling User Requirement

Module 20: How to develop code from use case and Architecture Model

MODULE 1: DESIGN PRINCIPLES AND PATTERNS IN SOFTWARE

FACTORY TOOLKITS

Stylize, edit, and animate your media

9

What Is a Good Software ?

Good software :

Work as intended

Easy to change

In a large organization :

Easily to maintain

อ.ประกอบ พงศป์ฏิเมธ

Good Software and Quality Attributes

Software Design Principle

Making software easily to change:

Design component loosely coupled.

Reduce the dependencies

Focus on maintainability quality attribute

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

Which Food Do You Like?

From spaghetti code to lasagna code

Cohesion

Coupling

Separation of Concerns

Identifying the concerns Modularity Information hiding SoC and programming

paradigms

Object Oriented Design

Basic OOD principles

Find pertinent Object first

Favor low coupling

Favor code reuse

Lab1: Building SimpleMVCApp

Time: 15 minutes

Create MVC Project using WebForm View Engine

Understand SimpleMVCApp

Running Application

Evaluation of MVP, MVC Patterns

Model-View-Controller (MVC)

Model-View-Controller (1980-1990)

Model-View-Controller (Generation2: MVC Framework)

Model-View-Presenter (MVP)

Smart Client Software Factory

Web Client Software Factory

Presentation-Model (PM)

WPF & Silverlight

อ.ประกอบ พงศป์ฏิเมธ

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.

อ.ประกอบ พงศป์ฏิเมธ

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?

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

•A design pattern

•Acronym for Model ● View ● Controller

•Separation of concerns

อ.ประกอบ พงศป์ฏิเมธ

ASP.NET MVC Is Part of the ASP.NET Framework

.NET Framework

ASP.NET Framework

ASP.NET MVC ASP.NET Web Forms

อ.ประกอบ พงศป์ฏิเมธ

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

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

Step 1

Incoming request directed to Controller

Request

Controller

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

Step 2

Controller processes request and forms a data Model

Controller

Model

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

Step 3

Model is passed to View

Controller

View

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

Step 4

View transforms Model into appropriate output format

Controller

View

อ.ประกอบ พงศป์ฏิเมธ

What is MVC?

Step 5

Response is rendered

Response

Controller

View

อ.ประกอบ พงศป์ฏิเมธ

ประโยชน์ของ MVC

ง่ายต่อการทดสอบช้ินงานของ User Interface

Separation of Concerns มีการแยกโคด้ของ Presentation Layer ออกเป็นส่วน ๆ ตามลกัษณะการท างานในรูปแบบ Low coupling และ

High Cohesion

อ.ประกอบ พงศป์ฏิเมธ

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

Create ClinicDB

Table GeneralMasterTypes

Table GeneralMasterCodes

Index Action

Details Actions

Create Action

Edit Action

Delete Action

Introduction to ASP.NET MVC Framework 3.0 and

Razor View Engine

Stylize, edit, and animate your media

39

ASP.NET MVC3.040

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

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.

Demo Create MVC Razor View Application

42

Razor View Engine Features43

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.vbhtmlfile for VB.NET

View Property44

Prepared by Prakob Pongpatimet

45

Razor View Engine & ASP.NET

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

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

Workshop: Create Razor View Engine

อ.ประกอบ พงศป์ฏิเมธ

Prepared by Prakob Pongpatimet

48

ASPX vs Razor Syntax

อ.ประกอบ พงศป์ฏิเมธ

Prepared by Prakob Pongpatimet

49

The Razor parser has semantic knowledge of

C#/VB code used within code-blocks .

Prepared by Prakob Pongpatimet

50

Razor Syntax

Prepared by Prakob Pongpatimet

51

Loop and Nested Html Sample

If Block and Multi Line Statement

อ.ประกอบ พงศป์ฏิเมธ

Prepared by Prakob Pongpatimet

52

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

Layout/MasterPage Scenarios – The Basics

อ.ประกอบ พงศป์ฏิเมธ

Prepared by Prakob Pongpatimet

54

Razor also supports this

concept using “layout

pages”

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

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

Prepared by Prakob Pongpatimet

56

_ViewStart.cshtml

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

Encapsulation and Re-Use with HTML Helpers

Code Based HTML Helpers

อ.ประกอบ พงศป์ฏิเมธ

Prepared by Prakob Pongpatimet

58

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 Views\Helpers directory

and then re-use them from any

view or page in your site

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.

Create MvcMovie application

Lab 4: MVCMovie Application

อ.ประกอบ พงศป์ฏิเมธ

62

63

You will learn64

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.

1. Creating Your First Application65

Create Mvc3 Application named “MvcMovie”

Internet Application

Razor View

2. Adding Controller66

Add HelloWorldController

Create Two Action Methods

Execute the application

Pass Some Parameter Information From URL

Create Two Action Methods67

Execute Application68

http://localhost:xxxx/HelloWorld

http://localhost:xxxx/HelloWorld/Welcome

Pass Some Parameter Information From

URL 69

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

3. Adding a View70

Add Index View

Changing Views and Layout Pages

Passing Data from the Controller to the View

Add Index View71

Add Html under h2

Run the application

Changing Views and Layout Pages72

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

Change Title of the Index Page 73

http://localhost:xx/HelloWorld

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.

Update Welcome Action75

Now the ViewBag object contains data that will be

passed to the view automatically.

Add Welcome View76

Add code under h2

http://localhost:xx/HelloWorld/Welcome?name=Sri

tang&numtimes=4

3. Add a Model77

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.")

Using NuGet to Install EFCodeFirst

78

Select Library Package Manager and

then Add Library Package Reference79

80

Install EFCodeFirst81

The Error Message82

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

Adding Model Classes83

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.

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

Create MovieController85

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.

Creating a Connection String and

Working with SQL Server Express 87

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" />

Create Movie Database88

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.

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

Create Action Method90

Add Create View

Execute /Movies/Create URL

Processing the HTTP-POST91

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.

Creating a Movie93

/Movies/Create URL

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

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.

Two Approaches to Resolve96

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.

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.

Add Class MovieIntializer in Model98

MovieIntializer99

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).

MovieIntializer100

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).

Open the Global.asax file101

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.

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

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.

Application_Start() in Golbal.asax104

Fixing the Precision of our Price105

EF code-first created our database, it used a

default precision setting of (18:0) when creating

columns for Decimal data-types.

Update Movie Model106

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;

Add OnModelCreating107

Add the following OnModelCreating override

method to our existing MovieDBContext class

6. Adding Validation to the Model108

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.

Adding Validation Rules to the Movie Model

109

Open Movie Model

using System.ComponentModel.DataAnnotations;

Update Movie Class110

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.

Validation Error UI within ASP.NET MVC

112

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.

114

7. Implementing Edit, Details, and Delete

115

Add Details Method to MovieController

Implementing Edit, Details, and Delete Views

Implementing Edit, Details, and

Delete Views116

Add Details Method117

Create Details View

Create Edit Action Method118

Create Edit Post Method119

Create Edit View120

Create Delete Method121

Create Delete View122

top related