ASP.NET Using C# - Training Materials for IT · PDF fileASP.NET MVC 4 Using C# Evaluation ......

73
Object Innovations Course 4143 Student Guide Revision 4.5 ASP.NET MVC 4 Using C# Evaluation Copy

Transcript of ASP.NET Using C# - Training Materials for IT · PDF fileASP.NET MVC 4 Using C# Evaluation ......

Page 1: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Object Innovations Course 4143

Student Guide

Revision 4.5

ASP.NET MVC 4

Using C#

Evaluation Copy

Page 2: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC iii

All Rights Reserved

Table of Contents (Overview)

Chapter 1 Introduction to ASP.NET MVC

Chapter 2 Getting Started with ASP.NET MVC

Chapter 3 ASP.NET MVC Architecture

Chapter 4 The Model

Chapter 5 The Controller

Chapter 6 The View

Chapter 7 Routing

Chapter 8 Unit Testing

Chapter 9 Security

Chapter 10 Combining ASP.NET MVC and Web Forms

Chapter 11 ASP.NET Web API

Appendix A Learning Resources

Appendix B Databases via Scaffolding and Code First

Appendix C Deployment in IIS 7.5

Evaluation Copy

Page 3: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC iv

All Rights Reserved

Directory Structure

The course software installs to the root directory

C:\OIC\MvcCs.

Example programs for each chapter are in named

subdirectories of chapter directories Chap02, Chap03, and so

on.

The Labs directory contains one subdirectory for each lab,

named after the lab number. Starter code is frequently supplied,

and answers are provided in the chapter directories.

The Demos directory is provided for doing in-class

demonstrations led by the instructor.

Data files install to the directory C:\OIC\Data.

Evaluation Copy

Page 4: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC v

All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Introduction to ASP.NET MVC ....................................................................... 1

Review of ASP.NET Web Forms ....................................................................................... 3

Advantages of ASP.NET Web Forms ................................................................................. 4

Disadvantages of ASP.NET Web Forms ............................................................................ 5

Model-View-Controller Pattern .......................................................................................... 6

ASP.NET MVC .................................................................................................................. 7

Advantages of ASP.NET MVC .......................................................................................... 8

Disadvantages of ASP.NET MVC ...................................................................................... 9

Goals of ASP.NET MVC .................................................................................................. 10

Unit Testing ...................................................................................................................... 11

Summary ........................................................................................................................... 12

Chapter 2: Getting Started with ASP.NET MVC ............................................................ 13

An ASP.NET MVC 4 Testbed .......................................................................................... 15

Visual Studio ASP.NET MVC Project ............................................................................. 16

New ASP.NET MVC 4 Project......................................................................................... 17

Starter Application ............................................................................................................ 18

Simple App with Controller Only ..................................................................................... 20

Action Methods and Routing ............................................................................................ 26

Action Method Return Type ............................................................................................. 27

Rendering a View ............................................................................................................. 28

Creating a View in Visual Studio ..................................................................................... 29

The View Web Page ......................................................................................................... 30

Dynamic Output ................................................................................................................ 31

Embedded Scripts ............................................................................................................. 32

Embedded Script Example ............................................................................................... 33

Using a Model ................................................................................................................... 34

Controller Using the Model .............................................................................................. 35

View Using the Model ...................................................................................................... 36

Strongly-Typed View ........................................................................................................ 37

Strongly-Typed View in Visual Studio ............................................................................. 38

Lab 2 ................................................................................................................................. 39

Summary ........................................................................................................................... 40

Chapter 3: ASP.NET MVC Architecture ......................................................................... 45

The Controller in ASP.NET MVC.................................................................................... 47

The View in ASP.NET MVC ........................................................................................... 48

The Model in ASP.NET MVC .......................................................................................... 49

How MVC Works ............................................................................................................. 50

Using Forms ...................................................................................................................... 51

HTML Helper Functions ................................................................................................... 52

Displaying Sign In Form ................................................................................................... 53

Evaluation Copy

Page 5: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC vi

All Rights Reserved

Handling Form Submission............................................................................................... 54

Model Binding .................................................................................................................. 55

Greet View ........................................................................................................................ 56

Input Validation ................................................................................................................ 57

Nullable Type.................................................................................................................... 58

Checking Model Validity .................................................................................................. 59

Validation Summary ......................................................................................................... 60

Lab 3 ................................................................................................................................. 61

Summary ........................................................................................................................... 62

Chapter 4: The Model ......................................................................................................... 71

Microsoft Technologies for the Model ............................................................................. 73

SmallPub Database ........................................................................................................... 74

ADO.NET ......................................................................................................................... 76

Language Integrated Query (LINQ) .................................................................................. 77

ADO.NET Entity Framework ........................................................................................... 78

EDM Example .................................................................................................................. 79

SmallPub Tables ............................................................................................................... 81

SmallPub Entity Data Model ............................................................................................ 82

Entity Data Model Concepts ............................................................................................. 83

Querying the EDM ............................................................................................................ 84

Class Diagram ................................................................................................................... 85

Context Class .................................................................................................................... 86

List of Categories .............................................................................................................. 87

List of Books ..................................................................................................................... 89

LINQ to Entities Demo ..................................................................................................... 91

A LINQ Query ................................................................................................................... 92

IntelliSense ........................................................................................................................ 93

Controller .......................................................................................................................... 94

Web.config ........................................................................................................................ 95

Using a Parameter ............................................................................................................. 96

Modifying a Data Source .................................................................................................. 97

LINQ to Entities Insert Example ...................................................................................... 99

LINQ to Entities Delete Example ................................................................................... 100

Entity Framework in a Class Library .............................................................................. 101

Data Access Class Library .............................................................................................. 102

Client Code ..................................................................................................................... 103

ASP.NET MVC Database Clients .................................................................................. 104

ASP.NET MVC Database Client Demo ......................................................................... 105

Lab 4 ............................................................................................................................... 110

NuGet Package Manager ................................................................................................ 111

Visual Studio Extensions ................................................................................................ 112

Online Gallery ................................................................................................................. 113

Entity Framework 5 via NuGet ....................................................................................... 114

Summary ......................................................................................................................... 115

Evaluation Copy

Page 6: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC vii

All Rights Reserved

Chapter 5: The Controller ............................................................................................... 121

IController Interface ....................................................................................................... 123

A Low Level Controller .................................................................................................. 124

Displaying Context ......................................................................................................... 125

Add and Subtract............................................................................................................. 126

Controller Base Class ...................................................................................................... 127

Controller Base Class ...................................................................................................... 128

Action Methods ............................................................................................................... 129

Action Method Example ................................................................................................. 130

HomeController .............................................................................................................. 131

MathController................................................................................................................ 132

Invoking MathController ................................................................................................ 133

Receiving Input ............................................................................................................... 134

Binding Example ............................................................................................................ 135

Non-Nullable Parameters ................................................................................................ 136

Nullable Parameters ........................................................................................................ 137

Using a Model ................................................................................................................. 138

Action Results ................................................................................................................. 139

Action Result Example ................................................................................................... 140

Output Demo ................................................................................................................... 141

JavaScript Object Notation ............................................................................................. 144

Action Method Attributes ............................................................................................... 145

HTML Output ................................................................................................................. 146

Filters .............................................................................................................................. 147

Asynchronous Controllers ............................................................................................... 149

Lab 5 ............................................................................................................................... 150

Summary ......................................................................................................................... 151

Chapter 6: The View ......................................................................................................... 159

View Responsibility ........................................................................................................ 161

A Program without a View ............................................................................................. 162

A Program with a View .................................................................................................. 163

View Page ....................................................................................................................... 164

Passing Data to the View ................................................................................................ 165

Passing Lists to the View ................................................................................................ 166

Strongly-Typed Views .................................................................................................... 167

Strongly-Typed View Example....................................................................................... 168

Strongly-Typed View in Visual Studio ........................................................................... 169

Passing Data with Dynamic Objects ............................................................................... 170

More about Dynamic Objects ......................................................................................... 171

HTML Helper Methods ................................................................................................... 172

Link-Building Helpers..................................................................................................... 173

Form Helpers ................................................................................................................... 174

Validation Helpers .......................................................................................................... 175

Templated Helpers .......................................................................................................... 176

Evaluation Copy

Page 7: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC viii

All Rights Reserved

Razor View Engine ......................................................................................................... 178

Razor View Example ...................................................................................................... 179

ViewBag.......................................................................................................................... 180

Validation in Model ........................................................................................................ 181

Validation in Controller .................................................................................................. 182

ValidationMessage Helper .............................................................................................. 183

Running the Example...................................................................................................... 184

Lab 6 ............................................................................................................................... 185

Summary ......................................................................................................................... 186

Chapter 7: Routing ........................................................................................................... 193

ASP.NET Routing ........................................................................................................... 195

Routing in ASP.NET MVC ............................................................................................ 196

RouteCollectionExtensions Class ................................................................................... 197

Simple Route Example ................................................................................................... 198

Default Values for URL Parameters ............................................................................... 200

Using a Default Route ..................................................................................................... 201

Home Controller ............................................................................................................. 202

Assigning Parameter Values ........................................................................................... 203

Controller Code............................................................................................................... 204

View Code ...................................................................................................................... 205

Running the Example...................................................................................................... 206

Properties of Routes ........................................................................................................ 207

UrlParameter.Optional .................................................................................................... 208

MvcUrlParameterOptional Example .............................................................................. 209

Running the Example...................................................................................................... 211

A Problem with the Route Map ...................................................................................... 212

Matching URLs to Route ................................................................................................ 213

Demo: Route Order ......................................................................................................... 214

Route Debugging Utility ................................................................................................. 218

Multiple Matches ............................................................................................................ 220

Fixing the Bug ................................................................................................................. 221

Debugging Routes ........................................................................................................... 222

Areas ............................................................................................................................... 223

Demo: Areas ................................................................................................................... 224

Summary ......................................................................................................................... 227

Chapter 8: Unit Testing .................................................................................................... 229

Test-Driven Development ............................................................................................... 231

Functional Tests .............................................................................................................. 232

Unit Tests ........................................................................................................................ 233

Test Automation ............................................................................................................. 234

Refactoring ...................................................................................................................... 235

Regression Testing .......................................................................................................... 236

Unit Testing in ASP.NET MVC ..................................................................................... 237

MVC Unit Test Example ................................................................................................ 238

Evaluation Copy

Page 8: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC ix

All Rights Reserved

A Test Class Library ....................................................................................................... 239

Installing NUnit via NuGet ............................................................................................. 240

The Model ....................................................................................................................... 241

Testing the Model ........................................................................................................... 242

Structure of Unit Tests .................................................................................................... 243

Assertions ........................................................................................................................ 244

NUnit Framework ........................................................................................................... 245

NUnit Assert Class .......................................................................................................... 246

Assert.AreEqual() ........................................................................................................... 247

More Assert Methods ...................................................................................................... 248

Test Case ......................................................................................................................... 249

Test Fixture ..................................................................................................................... 250

Test Runner ..................................................................................................................... 251

Installing NUnit Runner .................................................................................................. 252

Using nunit.exe ............................................................................................................... 253

More Tests ...................................................................................................................... 254

Ignoring Tests ................................................................................................................. 255

Fixing the Bug ................................................................................................................. 256

Testing Controllers ......................................................................................................... 257

Lab 8A ............................................................................................................................. 258

Classes with External Dependencies .............................................................................. 259

Dependency Injection ..................................................................................................... 260

Mocking Frameworks ..................................................................................................... 261

Using Moq....................................................................................................................... 262

MvcMortgage Example .................................................................................................. 263

Models............................................................................................................................. 264

Controller ........................................................................................................................ 265

Index View ...................................................................................................................... 266

Monthly Payment View .................................................................................................. 267

Unit Tests ........................................................................................................................ 268

Inversion of Control (IoC) Containers ............................................................................ 269

Lab 8B ............................................................................................................................. 270

Summary ......................................................................................................................... 271

Chapter 9: Security ........................................................................................................... 283

Web Security ................................................................................................................... 285

Input Forgery ................................................................................................................... 286

Cross-Site Scripting ........................................................................................................ 288

XSS Example .................................................................................................................. 290

Entering JavaScript ......................................................................................................... 292

The Attack ....................................................................................................................... 293

Defending Against the Attack ......................................................................................... 294

Session Hijacking ............................................................................................................ 295

Cross-Site Request Forgery ............................................................................................. 297

XSRF Example ............................................................................................................... 299

Evaluation Copy

Page 9: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC x

All Rights Reserved

Controller and Model Code ............................................................................................ 301

View Code ...................................................................................................................... 302

Attacker Code ................................................................................................................. 303

The Defense .................................................................................................................... 304

SQL Injection .................................................................................................................. 305

Using the MVC Framework Securely ............................................................................. 309

Authorize Attribute ......................................................................................................... 310

ChildActionOnly Attribute ............................................................................................. 311

RequireHttps Attribute .................................................................................................... 312

ValidateInput Attribute ................................................................................................... 313

Summary ......................................................................................................................... 314

Chapter 10: Combining ASP.NET MVC and Web Forms ............................................ 315

Using Web Forms in an MVC Application..................................................................... 317

Linking and Redirecting from Web Forms Pages to MVC Actions ............................... 318

Default.aspx .................................................................................................................... 319

Web Forms in MVC Example ........................................................................................ 320

Sharing Data between ASP.NET MVC and ASP.NET Web Forms ............................... 322

Using Web Form Controls in MVC Views ..................................................................... 323

Using MVC in a Web Forms Application....................................................................... 324

Steps to Create Hybrid MVC - Web Forms Application ................................................ 325

Lab 10 ............................................................................................................................. 327

Summary ......................................................................................................................... 328

Chapter 11: ASP.NET Web API...................................................................................... 333

ASP.NET Web API ......................................................................................................... 335

REST ............................................................................................................................... 336

Representation, State and Transfer ................................................................................. 337

Collections and Elements ............................................................................................... 338

Obtaining Web API with NuGet ..................................................................................... 339

Web API Demo ............................................................................................................... 340

Implementing PUT Verb................................................................................................. 343

Using Fiddler ................................................................................................................... 344

Composing a Request ..................................................................................................... 346

ASP.NET MVC and Web API ........................................................................................ 348

String API Demo ............................................................................................................. 349

Route Registration .......................................................................................................... 351

Lab 11A ........................................................................................................................... 354

HTTP Response Codes ................................................................................................... 355

POST Response Code ..................................................................................................... 356

HttpResponseException .................................................................................................. 357

Web API Clients ............................................................................................................. 358

HttpClient ........................................................................................................................ 359

Initializing HttpClient ..................................................................................................... 360

Issuing a GET Request .................................................................................................... 361

Issuing a POST Request .................................................................................................. 362

Evaluation Copy

Page 10: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC xi

All Rights Reserved

Lab 11B ........................................................................................................................... 363

Performing CRUD Operations ........................................................................................ 364

Books API Example ........................................................................................................ 365

Server Code: Model ........................................................................................................ 366

Book Repository ............................................................................................................. 367

BooksController .............................................................................................................. 369

View ................................................................................................................................ 371

Exercise the Server Using Fiddler .................................................................................. 372

Client Code: Book Class ................................................................................................. 373

Client Code: Program Class ............................................................................................ 374

ShowBooks() ................................................................................................................... 375

AddBook() ...................................................................................................................... 376

Update and Delete ........................................................................................................... 377

Summary ......................................................................................................................... 378

Appendix A:Learning Resources ..................................................................................... 389

Appendix B: Databases via Scaffolding and Code First ................................................ 393

Scaffolding in ASP.NET MVC 4 .................................................................................... 395

Entity Framework 5 Code First ....................................................................................... 396

Scaffolding and Code First Demo ................................................................................... 397

Summary ......................................................................................................................... 403

Appendix C: Deployment in IIS 7.5 ................................................................................. 405

Internet Information Services ......................................................................................... 406

Installing IIS 7.5 .............................................................................................................. 407

MVC with IIS 7.5 ............................................................................................................ 408

.NET Framework Version ............................................................................................... 409

Registering ASP.NET ..................................................................................................... 412

Demo: Running an MVC App on IIS .............................................................................. 413

Convert to an Application ............................................................................................... 414

XCOPY Deployment ...................................................................................................... 415

Lab C ............................................................................................................................... 416

Evaluation Copy

Page 11: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC xii

All Rights Reserved

Evaluation Copy

Page 12: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 1

All Rights Reserved

Chapter 1

Introduction to ASP.NET MVC

Evaluation Copy

Page 13: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 2

All Rights Reserved

Introduction to ASP.NET MVC

Objectives

After completing this unit you will be able to:

Describe advantages and disadvantages of ASP.NET

Web Forms.

Understand the Model-View-Controller (MVC)

pattern

Outline the parts of an ASP.NET MVC application.

Describe advantages and disadvantages of ASP.NET

MVC.

Understand the use of unit testing in creating

ASP.NET MVC applications.

Evaluation Copy

Page 14: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 3

All Rights Reserved

Review of ASP.NET Web Forms

ASP.NET Web Forms provide a way to build web

applications.

You can use compiled, object-oriented languages with

ASP.NET, including C# and Visual Basic.

All the power of the .NET Framework is available to you,

including the extensive class library.

Code and presentation elements can be cleanly

separated.

Code can be provided in a separate section of a Web page

from user interface elements.

The separation can be carried a step further by use of separate

“code behind” files.

ASP.NET Web Forms comes with an extensive set of

server controls that provide significant functionality

out of the box.

Server controls transparently handle browser

compatibility issues.

A special set of Mobile Controls can emit either HTML or

WML, depending on the characteristics of the client device.

Configuration is handled by XML files without need

of any registry settings, and deployment can be done

simply by copying files.

Evaluation Copy

Page 15: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 4

All Rights Reserved

Advantages of ASP.NET Web Forms

ASP.NET Web Forms continue to be supported and

have their own advantages:

A rich event model supported in hundreds of server controls

facilitates easy development of Web server applications,

following a familiar GUI development paradigm.

View state makes it easy to manage state information.

The model works well for individuals and small teams doing

rapid application development.

The large number of built-in and third-party components also

facilitates rapid application development.

In general, Web Forms are quite easy to work with

and generally require less code.

Evaluation Copy

Page 16: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 5

All Rights Reserved

Disadvantages of ASP.NET Web

Forms

Key disadvantages of ASP.NET Web Forms include

ViewState tends to be large depending on the number of

server controls contained on the page, thus increasing the size

of the page and the length of the response time from server to

browser

ASP.NET Web Forms provide tight coupling with the code-

behind classes which make automated testing of the back-end

code apart from the web pages more difficult

Because the code-behind classes are so tightly coupled to the

web forms, developers are encouraged to mix presentation

code with application logic in the same code-behind classes

which can lead to fragile and unintelligible code

Limited control of HTML rendered through use of server

controls

Evaluation Copy

Page 17: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 6

All Rights Reserved

Model-View-Controller Pattern

The Model-View-Controller (MVC) design pattern

divides an application into three conceptual

components:

A model represents the data and operations that are

meaningful to the domain of the application. It implements

the application logic for the domain.

Views display a user interface for portions of the model.

Typically the UI is created from model data.

Controllers handle incoming requests, work with the model,

and select a view to render a UI back to the user.

Controller

Model

View

User

Evaluation Copy

Page 18: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 7

All Rights Reserved

ASP.NET MVC

ASP.NET MVC is a framework based on ASP.NET

for creating Web applications.

It is an alternative to Web Forms.

ASP.NET MVC 1.0 is available as a separate

download and can be installed on top of .NET 3.5 SP1

and Visual Studio 2008 SP.

ASP.NET MVC 2.0 is integrated into .NET 4.0 and

Visual Studio 2010.

ASP.NET MVC 3.0 is a separate download and adds

important new features, such as the Razor view

engine.

ASP.NET MVC 4.0 is integrated into .NET 4.5 and

Visual Studio 2012. It is also available as a separate

download.

When you install ASP.NET MVC 4 on top of Visual Studio

2010, you will have ASP.NET MVC 2 and ASP.NET MVC

4 both available side by side.

ASP.NET MVC does not replace Web Forms but is

an alternative approach to creating Web applications.

It relies on the same ASP.NET infrastructure as does

Web Forms and is integrated with ASP.NET features

such as master pages and membership-based

authentication.

Evaluation Copy

Page 19: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 8

All Rights Reserved

Advantages of ASP.NET MVC

Key advantages of ASP.NET MVC include:

The MVC pattern promotes separation of concerns into

input logic (controller), business logic (model) and UI

(view). This aids in managing complexity.

These components are loosely coupled, promoting parallel

development.

This loose coupling also facilitates automated testing.

Views are created using standard HTML and cascading style

sheets, giving the developer a high degree of control over the

user interface.

There is no view state, reducing the load on the browser in

rendering a page.

Separation of Concerns:

Each component has one responsibility

SRP – Single Responsibility Principle

DRY – Don’t Repeat Yourself

More easily testable

Helps with concurrent development

Evaluation Copy

Page 20: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 9

All Rights Reserved

Disadvantages of ASP.NET MVC

Key disadvantages of ASP.NET MVC include:

Writing View contents the old ASP-like way (though there

are new View engines that are coming out).

Unit testing and Test Driven Development (TDD) are

encouraged and used more but also bring a steep learning

curve.

Need to understand HTML controls and style sheets, but at

the same time this allows a designer to work independently

of the coders.

Evaluation Copy

Page 21: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 10

All Rights Reserved

Goals of ASP.NET MVC

The ASP.NET MVC Framework has the following

goals:

Frictionless Testability

Tight control over markup

User/Search Engine friendly URLs

Leverage the benefits of ASP.NET

Conventions and Guidance

Extensibility

Replace any component of the system

Interface-based architecture

Very few sealed methods / classes

Evaluation Copy

Page 22: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 11

All Rights Reserved

Unit Testing

Unit testing lets you specify the expected behavior of

individual classes or other small code units in

isolation.

ASP.NET MVC encourages unit testing of the Models

and the Controllers of the application to verify

expected behaviors.

Separation of concerns makes unit testing of

individual components feasible.

You may use Microsoft’s MSTest for unit testing or

other unit test framework such as NUnit.

NUnit is free open source software and is used in this course.

It can be used with the free version of Visual Studio 2012,

Visual Web Developer Express 2012.

MSTest is built into Visual Studio 2012 Professional edition

and higher.

Evaluation Copy

Page 23: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 12

All Rights Reserved

Summary

ASP.NET Web Forms is still used and has many

advantages and disadvantages

The Model-View-Controller (MVC) pattern is useful

in creating applications that have separation of

concerns

ASP.NET MVC also has many advantages and

disadvantages in developing web applications

Unit testing is helpful and encouraged in developing

ASP.NET MVC applications

Evaluation Copy

Page 24: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 13

All Rights Reserved

Chapter 2

Getting Started with ASP.NET

MVC

Evaluation Copy

Page 25: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 14

All Rights Reserved

Getting Started with ASP.NET MVC

Objectives

After completing this unit you will be able to:

Install the ASP.NET MVC application framework.

Understand how ASP.NET MVC is used within

Visual Studio.

Create a Hello World application with ASP.NET

MVC.

Understand how Views are rendered.

Understand how dynamic output works.

Evaluation Copy

Page 26: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 15

All Rights Reserved

An ASP.NET MVC 4 Testbed

This courses uses the following software:

Visual Studio 2012. The course was developed using the

Professional Edition, but the free Visual Web Developer

Express 2012 should also be adequate.

This includes bundled ASP.NET MVC 4.

SQL Server 2012 LocalDB, which also comes bundled with

Visual Studio 2012.

Recommended operating system is Windows 7 SP1.

If you want to practice deployment on IIS, you should

also have IIS installed, which should be done before

installing Visual Studio 2012.

See Appendix C.

Evaluation Copy

Page 27: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 16

All Rights Reserved

Visual Studio ASP.NET MVC Project

Let’s use Visual Studio (or Visual Web Developer) to

create an ASP.NET MVC 4 Web Application project.

Note that Visual Studio 2012 also supports creating

ASP.NET MVC 3 applications.

Browse to the C:\OIC\MvcCs\Demos folder, and leave

the name as MvcApplication1.

Click OK.

Evaluation Copy

Page 28: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 17

All Rights Reserved

New ASP.NET MVC 4 Project

Select Internet Application.

MVC 4 adds templates for Mobile Application, Web API and

Basic Application.

A feature of MVC 3 and above is support of multiple

view engines. Select ASPX.

The default for MVC 4 is the Razor View Engine, which we

will discuss in Chapter 6.

Evaluation Copy

Page 29: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 18

All Rights Reserved

Starter Application

Notice that there are separate folders for Controllers,

Models and Views.

Evaluation Copy

Page 30: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 19

All Rights Reserved

Starter Application (Cont’d)

Build and run this starter application:

Evaluation Copy

Page 31: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 20

All Rights Reserved

Simple App with Controller Only

To start learning how ASP.NET MVC works, let’s

create a simple app with only a controller.

1. Create a new ASP.NET MVC 4 Web Application project with

the name MvcSimple in the Demos folder.

2. This time choose the Empty Project template.

Evaluation Copy

Page 32: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 21

All Rights Reserved

Demo: Controller Only (Cont’d)

3. Right-click over the Controllers folder and choose Add |

Controller from the context menu.

4. Provide the name HomeController

5. Under Scaffolding options choose Empty MVC controller for

the Template1.

6. Click Add.

1 In ASP.NET MVC4 there are also several options for API controllers. These will be discussed in Chapter

11, which introduces Web API, a major new feature available in ASP.NET MVC 4

Evaluation Copy

Page 33: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 22

All Rights Reserved

Demo: Controller Only (Cont’d)

7. Examine the generated code HomeController.cs.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace MvcSimple.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ActionResult Index()

{

return View();

}

}

}

Evaluation Copy

Page 34: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 23

All Rights Reserved

Demo: Controller Only (Cont’d)

8. Replace the code for the Index() method by the following. Also,

provide a similar Foo() method.

public class HomeController : Controller

{

//

// GET: /Home/

public string Index()

{

return "Hello from Index";

}

public string Foo()

{

return "Hello from Foo";

}

}

9. Build and run.

10. Examine the URL Visual Studio used to invoke the

application. (Naturally the port number varies.)

http://localhost:51148/

Evaluation Copy

Page 35: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 24

All Rights Reserved

Demo: Controller Only (Cont’d)

11. Now try using these URLs2. You should get the same result.

http://localhost:51148/Home/

http://localhost:51148/Home/Index/

12. Now try this URL.

http://localhost:51148/Home/Foo/

You will see the second method Foo() invoked:

13. Finally, let’s add a second controller SecondController.cs.

2 The trailing forward slash in these URLs is optional.

Evaluation Copy

Page 36: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 25

All Rights Reserved

Demo: Controller Only (Cont’d)

14. Provide the following code for the Index() method of the

second controller.

public class SecondController : Controller

{

//

// GET: /Second/

public string Index()

{

return "Hello from second controller";

}

}

15. You can invoke this second controller using either of these

URLs:

http://localhost:51148/Second/

http://localhost:51148/Second/Index/

In either case we get the following result. The program at this point

is saved in MvcSimple\Controller in the chapter folder.

Evaluation Copy

Page 37: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 26

All Rights Reserved

Action Methods and Routing

Every public method in a controller is an action

method.

This means that the method can be invoked by some URL.

The ASP.NET MVC routing mechanism determines

how each URL is mapped onto particular controllers

and actions.

The default routing is specified in the Global.asax.cs

file.

public class MvcApplication :

System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(

GlobalConfiguration.Configuration);

FilterConfig.RegisterGlobalFilters(

GlobalFilters.Filters);

RouteConfig.RegisterRoutes(

RouteTable.Routes);

BundleConfig.RegisterBundles(

BundleTable.Bundles);

AuthConfig.RegisterAuth(); }

}

We will discuss routing later.

Evaluation Copy

Page 38: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 27

All Rights Reserved

Action Method Return Type

An action method normally returns a result of type

ActionResult.

An action method can return any type, such as string, int,

and so on, but then the return value is wrapped in an

ActionResult.

The most common action of an action method is to

call the View() helper method, which returns a result

of type ViewResult, which derives from ActionResult.

The table shows some of the important action result

types, which all derive from ActionResult.

Action Result Helper Method Description

ViewResult View() Renders a view as a Web page,

typically HTML

RedirectResult Redirect() Redirects to another action

method using its URL

JsonResult Json() Returns a serialized Json

object

FileResult File() Returns binary data to write to

the response

Evaluation Copy

Page 39: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 28

All Rights Reserved

Rendering a View

Our primitive controllers simply returned a text

string to the browser.

Normally, you will want an HTML page returned.

This is done by rendering a view.

The controller will return a ViewResult using the helper

method View().

public ViewResult Index()

{

return View();

}

Try doing this in the MvcSimple program. Build and

run.

Evaluation Copy

Page 40: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 29

All Rights Reserved

Creating a View in Visual Studio

The error message is quite informative!

Let us create an appropriate file Index.aspx in the folder

Views/Home.

In Visual Studio you can create a view by right-

clicking in the action method. Choose Add View.

Continue to use the ASPX view engine.

Clear the check box for master page and click Add

Evaluation Copy

Page 41: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 30

All Rights Reserved

The View Web Page

A file Index.aspx is created in the Views\Home folder.

Edit this file to display a welcome message from the view.

To make it stand out, use H2 format.

Note that this page inherits from the ViewPage class3.

<%@ Page Language="C#"

Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>

<head runat="server">

<title>Index</title>

</head>

<body>

<h2>Hello from the View</h2>

</body>

</html>

Build and run.

3 The template parameter <dynamic> is new in .NET 4.0. Many of our programs won’t use it. Chapter 6

discusses this topic.

Evaluation Copy

Page 42: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 31

All Rights Reserved

Dynamic Output

The ViewPage class has a property ViewData that can

be used for passing data from the controller to the

view, enabling the rendering of dynamic output.

ViewData is of type ViewDataDictionary, which stores data

named by string keys.

This code in the controller stores the current time.

public ViewResult Index()

{

ViewData["time"] =

DateTime.Now.ToLongTimeString();

return View();

}

This markup in the view page displays the data.

<h2>Hello from the View</h2>

<%= ViewData["time"] %>

Here is a run:

The program is saved in MvcSimple\View.

Evaluation Copy

Page 43: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 32

All Rights Reserved

Embedded Scripts

The view page illustrates use of embedded C# script.

This feature is commonly used in ASP.NET MVC.

There are two forms of embedded script.

The pair <%= ... %> delimits an expression which is

converted to a string and outputted.

<%= ViewData["time"] %>

The pair <% ... %> delimits programming statements that do

not result in output.

<%

int day = 0;

while (day < 12)

{

%>

Evaluation Copy

Page 44: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 33

All Rights Reserved

Embedded Script Example

See MvcSimple\Script.

<%

int day = 0;

int gifts = 0;

int total = 0;

while (day < 12)

{

day += 1;

gifts += day;

total += gifts;

%>

On day <%= day%> number of gifts = <%= gifts%><br/>

<% } %>

<p>Total number of gifts = <%= total %></p>

Evaluation Copy

Page 45: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 34

All Rights Reserved

Using a Model

Our next version of the program uses a model.

See MvcSimple\Model in the chapter folder.

The model contains a class defining a Person.

See the file Person.cs in the Models folder of the project.

There are public properties Name and Age.

Unless otherwise assigned, Name is “John” and Age is 33.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MvcSimple.Models

{

public class Person

{

public string Name { get; set; }

public int Age { get; set; }

public Person()

{

Name = "John";

Age = 33;

}

}

}

Evaluation Copy

Page 46: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 35

All Rights Reserved

Controller Using the Model

The controller instantiates a Person object and passes

it in ViewData.

Note that we need to import the MvcSimple.Models

namespace.

using MvcSimple.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace MvcSimple.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ViewResult Index()

{

ViewData["person"] = new Person();

return View();

}

}

}

Evaluation Copy

Page 47: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 36

All Rights Reserved

View Using the Model

The view displays the output using appropriate

script.

Again we need to import the MvcSimple.Models namespace.

<%@ Page Language="C#"

Inherits="System.Web.Mvc.ViewPage" %>

<%@ Import Namespace="MvcSimple.Models" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 T...>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Model Demo</title>

</head>

<body>

<%

Person p = (Person)ViewData["person"];

%>

<h2>Using model data:</h2>

<p>Name = <%= p.Name %> </p>

<p>Age = <%= p.Age %> </p>

</body>

</html>

The output:

Evaluation Copy

Page 48: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 37

All Rights Reserved

Strongly-Typed View

You may pass a single model object to a view through

the use of a strongly-typed view.

For an example see MvcSimple\StronglyTyped.

To see how this works, first rewrite the controller.

public ViewResult Index()

{

Person p = new Person();

return View("Index", p);

}

The first parameter to the overload of the View() method is

the name of the view, and the second parameter is a model

object.

Next, rewrite the view page.

<%@ Page Language="C#" Inherits=

"System.Web.Mvc.ViewPage<MvcSimple.Models.Person>"

%>

...

<body>

<h2>Using model data:</h2>

<p>Name = <%= Model.Name %> </p>

<p>Age = <%= Model.Age%> </p>

</body>

</html>

The class Person is passed as a type parameter to the generic

ViewPage class, and the model object can be accessed

through the variable Model.

We no longer need the script code casting to a Person.

Evaluation Copy

Page 49: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 38

All Rights Reserved

Strongly-Typed View in Visual Studio

To create a view in Visual Studio, right-click inside

an action method and choose Add View from the

context menu.

You may create a strongly-typed view by selecting a

view data class (model) from the dropdown.

You should build the application first in order that the

dropdown be populated.

Evaluation Copy

Page 50: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 39

All Rights Reserved

Lab 2

Contact Manager Application

In this lab you will implement an ASP.NET MVC application that

creates a contact and displays it on the page. The lab previews the

use of forms and HTML helper methods.

Detailed instructions are contained in the Lab 2 write-up at the end

of the chapter.

Suggested time: 30 minutes

Evaluation Copy

Page 51: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 40

All Rights Reserved

Summary

You can begin creating an ASP.NET MVC

application with the controller, which handles various

URL requests.

From an action method of a controller you can create

a view using Visual Studio.

You can pass data from the controller to the view by

using the ViewData dictionary.

With a model you can encapsulate the business data

and logic.

You can pass a single model object from a controller

to a view through the use of a strongly-typed view.

Evaluation Copy

Page 52: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 41

All Rights Reserved

Lab 2

Contact Manager Application

Introduction

In this lab you will implement an ASP.NET MVC application that creates a contact and

displays it on the page. The lab previews the use of forms and HTML helper methods.

Suggested Time: 30 minutes

Root Directory: C:\OIC\MvcCs

Directories: Labs\Lab2 (do your work here)

Chap02\MvcContact (solution)

Instructions

1. Create a new ASP.NET MVC 4 Empty Web Application MvcContact with ASPX

View Engine in the working directory.

2. Create a new Contact model class under the Models folder of your new project.

Include the following string properties: FirstName and LastName.

3. Add a HomeController to the project.

4. Add a view corresponding to the Index() action method. Do not use a layout or

master page.

5. Make the title of the view “Contact Manager”. Provide text boxes for inputting

FirstName and LastName using Html helper methods. Provide a submit button with

value “Save Contact”.

<html>

<head runat="server">

<meta name="viewport" content="width=device-width" />

<title>Contact Manager</title>

</head>

<body>

<% Html.BeginForm(); %>

<p>First Name: <%= Html.TextBox("FirstName") %></p>

<p>Last Name: <%= Html.TextBox("LastName") %></p>

<input type="submit" value=" Save Contact " />

<% Html.EndForm(); %>

</body>

</html>

6. Build and run the application. You should see the input form displayed.

Evaluation Copy

Page 53: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 42

All Rights Reserved

7. Provide another Index() action method to respond to an HTTP POST from the form.

Supply the appropriate attributes to make the first method respond to GET and the

second method to POST. In the second method provide a parameter of type Contact.

//

// GET: /Home/

[AcceptVerbs(HttpVerbs.Get)]

public ActionResult Index()

{

return View();

}

//

// POST: /Home/

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Index(Contact contact)

{

ViewData["contact"] = contact;

return View();

}

8. Import the namespace MvcContact.Models so that you can access the Contact class.

9. Build the project to make sure you get a clean compile.

10. Inside the body of the Index view, below the Html.EndForm() helper method,

provide code that will display the contact information if the ViewData["contact"]

has been populated.

<% Contact contact = ViewData["contact"] as Contact; %>

<% if (contact != null) { %>

<p>

New Contact:<br/>

<%= contact.FirstName %> <%= contact.LastName %>

</p>

<% } %>

11. Add an import of the namespace MvcContacts.Models to top of the Index view

under the <@ Page %> directive.

<%@ Import Namespace="MvcContact.Models" %>

12. Build and run. Enter some data for First Name and Last Name. You should see output

something like this:

Evaluation Copy

Page 54: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 43

All Rights Reserved

13. You are done!

Evaluation Copy

Page 55: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 44

All Rights Reserved

Evaluation Copy

Page 56: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 315

All Rights Reserved

Chapter 10

Combining ASP.NET MVC and

Web Forms

Evaluation Copy

Page 57: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 316

All Rights Reserved

Combining ASP.NET MVC and Web Forms

Objectives

After completing this unit you will be able to:

Describe how Web Forms can be used in an

ASP.NET MVC application.

Describe how ASP.NET MVC can be used in a Web

Forms application.

Evaluation Copy

Page 58: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 317

All Rights Reserved

Using Web Forms in an MVC

Application

Despite enormous conceptual differences between

ASP.NET Web Forms and ASP.NET MVC, the

technologies’ shared underlying infrastructure makes

them fairly easy to integrate.

Great integration within ASP.NET

All the same providers still work

Membership, Session, Caching, etc.

ASP.NET Designer Surface in VS 2008, VS 2010, and

VS2012

It is much easier to use a Web Forms page in an

existing MVC application than using MVC in an

existing Web Forms application.

Evaluation Copy

Page 59: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 318

All Rights Reserved

Linking and Redirecting from Web

Forms Pages to MVC Actions

If you are targeting .NET Framework 4.0, your Web

Forms pages have built-in support for routing.

You can generate URLs and perform redirection to MVC

actions as follows:

protected void Page_Load(object sender,

EventArgs e)

{

// You can generate a URL based on routing

// parameters

string url = Page.GetRouteUrl( new {

controller = "Home", action = "Index" });

// ... or you can redirect to a location based

// on routing parameters

Response.RedirectToRoute(new {

controller = "Home", action = "Index" });

}

Evaluation Copy

Page 60: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 319

All Rights Reserved

Default.aspx

Typically, IIS is set by default to redirect to

Default.aspx when a browser navigates to your site

using a "/" as the end point of the URL.

You may want to include a Default.aspx page in your

MVC application in order to redirect requests for "/"

to the default MVC handler.

Add this code in the code-behind file in order to

redirect requests for Default.aspx to the default MVC

handler:

public void Page_Load(object sender, EventArgs e)

{

// Change the current path so that the Routing

// handler can correctly interpret

// the request, then restore the original path

// so that the OutputCache module

// can correctly process the response (if

// caching is enabled).

string originalPath = Request.Path;

HttpContext.Current.RewritePath(

Request.ApplicationPath, false);

IHttpHandler httpHandler =

new MvcHttpHandler();

httpHandler.ProcessRequest(

HttpContext.Current);

HttpContext.Current.RewritePath(

originalPath, false);

}

Evaluation Copy

Page 61: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 320

All Rights Reserved

Web Forms in MVC Example

This example illustrates using Web Forms in an

ASP.NET MVC application.

See MvcWithWebForms in the chapter folder.

Building and running the example project, you see this:

There is a link to an ordinary Web Forms page.

<html>

<head runat="server">...

<title>ASP.NET MVC Page</title>

</head>

<body>

<h1>This page uses ASP.NET MVC</h1>

<a href="WebForm1.aspx">

Click here to see a page using Web Forms</a>

</body>

</html>

Click this link.

Evaluation Copy

Page 62: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 321

All Rights Reserved

Web Forms in MVC Example (Cont’d)

There is a link back to the MVC page.

<head runat="server">

<title>Web Forms Page</title>

</head>

<body>

<h1>This page uses Web Forms</h1>

<a href="/">

Click here to see a page using ASP.NET MVC</a>

</body>

</html>

Click on this link, and you will get back.

Evaluation Copy

Page 63: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 322

All Rights Reserved

Sharing Data between ASP.NET MVC

and ASP.NET Web Forms

Because the ASP.NET MVC framework is built on

top of ASP.NET Web Forms, the following objects

are always available in both technologies:

HttpContext

Session

Server

Request

Response

Cookies

Here is an example of storing a value in the Session

object in a Web Form code-behind:

protected void Page_Load(object sender,EventArgs e)

{

Session["Msg"] = "Message from ASP.NET";

}

And an example of retrieving the shared Session

object in an MVC action method:

public ActionResult Index()

{

ViewData["Message"] = "ASP.NET MVC!";

ViewData["Shared"] = Session["Msg"] ?? "";

return View();

}

Evaluation Copy

Page 64: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 323

All Rights Reserved

Using Web Form Controls in MVC

Views

In some cases, you can drop an existing ASP.NET

server control into an MVC view.

This works for render-only controls that generate

HTML but don’t issue postbacks to the server.

Some example controls are SiteMapPath and Repeater

To set control properties or invoke data binding against

ViewData or Model contents, you can do so by putting a

<script runat=”server”> block anywhere in your view page.

Here is an example of binding to a Repeater control:

<script runat="server">

protected void Page_Load(object sender,

EventArgs e)

{

MyRepeater.DataSource =

ViewData["products"];

MyRepeater.DataBind();

}

</script>

Evaluation Copy

Page 65: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 324

All Rights Reserved

Using MVC in a Web Forms

Application

In order to use MVC in a Web Forms application,

several steps must be performed to convert the

existing Web Forms application to understand how to

use routing, controllers, and views.

Once the transformation of the project is complete,

you can begin to leverage the features of MVC (such

as REST-like URLs, separation of concerns,

testability, etc.) alongside your existing ASP.NET

pages.

There are two types of ASP.NET web applications in

Visual Studio: web site projects and web application

projects (both use Web Forms, but are distinctly

different).

You can only convert a web application project and not a

web site project to work with MVC.

First, convert your web site project to a web application

project (not covered here) and then proceed with the steps to

convert your new web application project into a hybrid MVC

- Web Forms application.

Evaluation Copy

Page 66: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 325

All Rights Reserved

Steps to Create Hybrid MVC - Web

Forms Application

These are the steps needed to convert an existing Web

Forms application into a Hybrid MVC - Web Forms

application:

Add a reference to System.Web.Mvc.dll - you will need to

browse for it under C:\Program Files\Microsoft ASP.NET\

ASP.NET MVC 4\Assemblies.

Add a reference to System.Web.Routing

Create an Empty MVC Project

a) Copy the Controllers, Models and Views directories

into the Web Forms application

b) Copy the RouteConfig.cs file in the App_Start folder

of the MVC project to the App_Start folder of the Web

Forms project in the Web Forms project. Edit the

namespace to work with the current project.

c) Call

RouteConfig.RegisterRoutes(RouteTable.Routes); in

Application_Start() in the Web Forms project

d) Add using System.Web.Mvc; and using

System.Web.Routing; to the Global.asax file in the Web

Forms project

Add the following to the <compilation> section of

web.config:

Evaluation Copy

Page 67: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 326

All Rights Reserved

Steps to Create Hybrid MVC - Web

Forms Application (Cont’d)

<assemblies>

<add assembly="System.Web.Abstractions,

Version=4.0.0.0, Culture=neutral,

PublicKeyToken=31bf3856ad364e35" />

<add assembly="System.Web.Routing,

Version=4.0.0.0, Culture=neutral,

PublicKeyToken=31bf3856ad364e35" />

<add assembly="System.Web.Mvc, Version=4.0.0.0,

Culture=neutral,

PublicKeyToken=31bf3856ad364e35" />

</assemblies>

Add the following to the <pages> section of web.config:

<namespaces>

<add namespace="System.Web.Mvc" />

<add namespace="System.Web.Mvc.Ajax" />

<add namespace="System.Web.Mvc.Html" />

<add namespace="System.Web.Routing" />

</namespaces>

Enable MVC Tooling in Web Form Application

a) Right-click on project and select unload.

b) Right-click on project and select Edit .csproj.

c) In <ProjectTypeGuids> section add at beginning of list

of Guids appropriate GUID copied from an MVC .csproj.

d) Right-click on project and select reload.

Close and reopen the solution

Evaluation Copy

Page 68: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 327

All Rights Reserved

Lab 10

Converting an Existing Web Forms Application to Work with

MVC

In this lab you will convert an existing ASP.NET Web Forms

application to work with ASP.NET MVC.

Detailed instructions are contained in the Lab 10 write-up at the

end of the chapter.

Suggested time: 45 minutes

Evaluation Copy

Page 69: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 328

All Rights Reserved

Summary

Because ASP.NET MVC sits on top of the ASP.NET

Framework, Web Forms will work as expected in an

MVC application.

Many common objects such as HttpContext, Session,

Server, etc. can be used in both technologies.

Using a Web Forms page in an MVC application is

easy.

To use ASP.NET MVC in an existing Web Forms

application you will need to go through several steps

to convert the Web Forms application.

Evaluation Copy

Page 70: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 329

All Rights Reserved

Lab 10

Converting an Existing Web Forms Application to Work with MVC

Introduction

In this lab you will convert an existing ASP.NET Web Forms application to work with

ASP.NET MVC.

Suggested Time: 45 minutes

Root Directory: C:\OIC\MvcCs

Directories: Labs\Lab10 (do your work here)

Chap10\MvcConvertWebForms\Step1 (solution to Part 1)

Chap10\MvcConvertWebForms\Step2 (solution to Part 2)

Chap10\MvcConvertWebForms\Step3 (solution to Part 3)

Part 1. Create Web Forms Application

1. Create a new ASP.NET Web Forms Application MvcConvertWebForms in the

working directory.

2. Build and run the application. You should see the following form displayed.

3. You are now at Step 1.

Evaluation Copy

Page 71: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 330

All Rights Reserved

Part 2. Convert Web Forms Application to use MVC

1. Continue working with the existing MvcConvertWebForms application created in

Step 1.

2. Add a reference to System.Web.Mvc.dll – you will need to browse for it under

C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies.

3. Add a reference to System.Web.Routing.

4. Add new folders Controllers and Views to the Web Forms application.

5. Copy the RouteConfig.cs file in the App_Start folder of the MVC project to the in

App_Start folder of the Web Forms project. Change the namespace to

MvcConvertWebForms.

6. Add a call to RouteConfig.RegisterRoutes(RouteTable.Routes); in the

Application_Start() method in the Web Forms project.

7. Import the namespaces System.Web.Mvc and System.Web.Routing to the

Global.asax.cs file in the Web Forms project.

8. Build and verify the application compiles. Run the application and it should still look

like a Web Forms application at this point. (If you have trouble running it, make sure

that Default.aspx is the Start Page.)

The next step is to add several assemblies to the web.config file. This will requiring

knowing the public key token of the assemblies. You can find that using the sn command

from a Visual Studio command prompt. Here is the syntax:

sn -Tp [pathToAssembly]\[assemblyFileName]

For convenience we’ve provided the batch file PublicKey.bat in the working directory to

execute this command with appropriate parameters.

9. Add the following to the <compilation> section under <system.web> of web.config

in the Web Forms project:

<assemblies>

<add assembly="System.Web.Abstractions, Version=4.0.0.0,

Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

<add assembly="System.Web.Routing, Version=4.0.0.0,

Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral,

PublicKeyToken=31bf3856ad364e35" />

</assemblies>

10. Add the following additional namespaces to the <pages> section of web.config in the

Web Forms project

Evaluation Copy

Page 72: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 331

All Rights Reserved

<namespaces>

<add namespace="System.Web.Optimization" />

<add namespace="System.Web.Mvc" />

<add namespace="System.Web.Mvc.Ajax" />

<add namespace="System.Web.Mvc.Html" />

<add namespace="System.Web.Routing" />

</namespaces>

11. We will need to enable MVC Tooling in the Web Forms Application. Close the Web

Forms project.

12. Open the file MvcWithWebForms.csproj as a text file. In <ProjectTypeGuids>

section copy from the list of Guids: E3E379DF-F4C6-4180-9B81-6769533ABE47;

13. Open the file MvcConvertWebForms.csproj as a text file. In <ProjectTypeGuids>

section at beginning of list of Guids paste the Guid you copied from the MVC project

file. Save the file, and then close it.

14. Open the solution.

15. Build and verify the application compiles. Run the application and it should still look

like a Web Forms application at this point.

16. You are now at Step 2.

Part 3. Use New Hybrid MVC-Web Forms Application with Default Web Forms

1. Continue working with the existing MvcConvertWebForms application modified in

Step 2.

2. In the Default.aspx page, add the following code at the top of the Main Content

section:

<p>

<a href="/Home/Index">ASP.NET MVC Home Page</a>

</p>

3. Add a HomeController to the project. (You can do this because of the MVC tooling

we enabled in Part 2.)

4. Add an ASPX view corresponding to the Index() action method. Do not select a

layout or master page.

5. Make the title of the view “Hello from MVC”. Add code in the body to say "This

page is rendering through MVC". Delete the <dynamic> from the Page directive.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html>

Evaluation Copy

Page 73: ASP.NET Using C# - Training Materials for IT  · PDF fileASP.NET MVC 4 Using C# Evaluation ... LINQ to Entities Insert Example ... HTML Output

MvcCs Chapter 10

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 332

All Rights Reserved

<html>

<head runat="server">

<meta name="viewport" content="width=device-width" />

<title>Hello from MVC</title>

</head>

<body>

This page is rendering through MVC

</body>

</html>

6. Set Default.aspx as the start page. Build and run the application. You should see the

following form:

7. Click on the ASP.NET MVC Home Page link and you get this. You are at Step 3.

Evaluation Copy