10264A Developing Web Applications with Microsoft Visual Studio 2010

download 10264A Developing Web Applications with Microsoft Visual Studio 2010

of 180

Transcript of 10264A Developing Web Applications with Microsoft Visual Studio 2010

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    1/180

    O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

    10264A

    Developing Web Applications withMicrosoft Visual Studio 2010

    Companion Content

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    2/180

    Information in this document, including URL and other Internet Web site references, is subject to change

    without notice. Unless otherwise noted, the example companies, organizations, products, domain names,

    e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with

    any real company, organization, product, domain name, e-mail address, logo, person, place or event is

    intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the

    user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in

    or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,

    photocopying, recording, or otherwise), or for any purpose, without the express written permission of

    Microsoft Corporation.

    Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property

    rights covering subject matter in this document. Except as expressly provided in any written license

    agreement from Microsoft, the furnishing of this document does not give you any license to these

    patents, trademarks, copyrights, or other intellectual property.

    The names of manufacturers, products, or URLs are provided for informational purposes only and

    Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding

    these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a

    manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links

    may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not

    responsible for the contents of any linked site or any link contained in a linked site, or any changes or

    updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission

    received from any linked site. Microsoft is providing these links to you only as a convenience, and the

    inclusion of any link does not imply endorsement of Microsoft of the site or the products contained

    therein.

    2010 Microsoft Corporation. All rights reserved.

    Microsoft and the trademarks listed at

    http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspxare trademarks

    of the Microsoft group of companies. All other marks are property of their respective owners.

    Product Number: 10264A

    Released: 11/2010

    http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspxhttp://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    3/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    4/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    5/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    6/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    7/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    8/180

    1-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Overview of IIS 7.0

    Contents:

    Question and Answers 3Detailed Demo Steps 4

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    9/180

    Overview of Web Application Architecture and Design 1-3

    Question and Answers

    Key Features of IIS 7.0

    Question:Which benefits are offered by the modular IIS architecture? Name at least one.

    Answer: You can quickly and easily add new features, you can make changes to one feature, which

    should not affect other features, and you can turn features on and off depending on your needs.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    10/180

    1-4 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Administering IIS 7.0 by Using IIS Manager

    This demonstration will illustrate the many features of IIS, and show how to administer its functions. These

    features include:

    Creating a new website

    Authentication

    Permissions

    Connection strings

    Application settings

    Starting and stopping a site

    Recycling the Application pool

    Create a new Website

    1. On the Startmenu, point to Administrative Tools, right-click Internet Information Services

    (IIS) Manager, and then click Run as administrator.

    In the User Account Controldialog box, in the Passwordbox, type Pa$$w0rd, and

    then click Yes.

    2.

    In Internet Information Services (IIS) Manager, expand 10264A-GEN-DEV (10264A-GEN-

    DEV\Admin), and then expand Sites.

    3.

    Right-click Sites, and then click Add Web Site.

    4.

    In the Add Web Sitedialog box, specify the settings as shown in the following sample. You will

    need to create the demosubfolder in the C:\inetpub\folder.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    11/180

    Overview of Web Application Architecture and Design 1-5

    5.

    Click OK.

    Change authentication

    1.

    In the Connectionspane, click Demo.

    2.

    In the Demo Homepane, in the IISsection, double-click Authentication.

    3.

    In the Authenticationpane, right-click Basic Authentication, and then click Enable.

    Edit permissions

    1. In the Connectionspane, click Demo.

    2.

    In the Actionspane, click Edit Permissions.

    3. In the demo Propertiesdialog box, click Security.

    4. Click Edit.

    5.

    In the Permissions for demodialog box, click Add.

    6.

    In the Select Users or Groupsdialog box, in the Enter the object names to selectbox, type

    IIS_IUSRS, click Check Names, and then click OK.

    7. In the Permissions for demodialog box, click OK.

    8. In the demo Propertiesdialog box, click OK.

    Set connection string

    1.

    In the Connectionspane, click Default Web Site, and then click Demo.

    2. In the Demo Homepane, in the ASP.NETsection, double-click Connection Strings.

    3.

    In the Actionspane, click Add.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    12/180

    1-6 Developing Web Applications with Microsoft Visual Studio 2010

    4.

    In the Add Connection Stringdialog box, specify the settings as shown in the following

    illustration.

    5.

    Click OK.

    6.

    In the Connection Stringspane, click Content View.

    7.

    In the Demo Contentpane, click web.config.Note:A web.config file is added to the websites root directory.

    8.

    In the Connectionspane, right-click Demo, and then click Explore.

    9.

    In Windows Explorer, double-click web.config.

    Note:In Microsoft Visual Studio 2010, you can see the new connection string added to theweb.config file.

    10. Close Microsoft Visual Studio 2010.

    11.

    Close Windows Explorer.

    Specify application settings

    1.

    In the Connectionspane, click Default Web Site, and then click Demo.

    2. In the Demo Contentpane, click Features View.

    3. In the Demo Homepane, in the ASP.NETsection, double-click Application Settings.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    13/180

    Overview of Web Application Architecture and Design 1-7

    4.

    In the Actionspane, click Add.

    5.

    In the Add Application Settingdialog box, specify the settings per the following.

    6.

    Click OK.

    7.

    In Windows Explorer, double-click web.config.

    Note:In Microsoft Visual Studio 2010, you can see the new application setting added to theweb.config file.

    8.

    Close Microsoft Visual Studio 2010.

    9.

    Close Windows Explorer.

    Restart the Website

    1. In the Connectionspane, click Default Web Site, and then click Demo.

    2. In Actionspane, in the Manage Web Sitesection, click Restart.

    Recycle an application pool

    1. In the Connectionspane, click Application Pools.

    2. In the Application Poolspane, click DefaultAppPool, and then in the Actionspane, in the

    Application Pool Taskssection, click Recycle.

    3.

    Close Internet Information Services (IIS) Manager.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    14/180

    1-8 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 2

    Overview of ASP.NET 4.0

    Contents:

    Question and Answers 9

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    15/180

    Overview of Web Application Architecture and Design 1-9

    Question and Answers

    New Features in ASP.NET 4.0

    Question:How is compression of serialized session state enabled?

    Answer: Compression of serialized session state is enabled by setting the value of the

    compressionEnabledconfiguration option to true.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    16/180

    1-10 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 3

    Introduction to the MVC Framework

    Contents:

    Question and Answers 11Detailed Demo Steps 12

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    17/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    18/180

    1-12 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Exploring an MVC Application

    Exploring the Adventure Works MVC Application

    1.

    Open Microsoft Visual Studio 2010.

    On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2. Create a new MVC project.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click New

    Project, or press CTRL+SHIFT+N.

    b.

    In the New Projectdialog box, in the left pane, in the Installed Templatessection,

    expand Visual C#or Visual Basic, and then click Web.

    c.

    In the New Projectdialog box, in the middle pane, click ASP.NET MVC 2 Web

    Application.d.

    In the New Projectdialog box, in the middle pane, in the Namebox, type

    DemoMvcApplication, in the Locationbox, type D:\Demofiles\Module 01\Demo 02,

    and then click OK.

    3. In the Create Unit Testdialog box, select the No, do not create a unit test projectoption, and

    then click OK.

    4.

    View the Controllersfolder.

    In Solution Explorer, expand the Controllersfolder.

    Note:Observe that the code files all have the suffix Controller.

    5.

    View the Modelsfolder

    In Solution Explorer, expand the Modelsfolder.

    6. View all the code in the AccountModelscode file.

    a. In Solution Explorer, double-click the AccountModels.csor AccountModels.vbcode

    file.

    b.

    In the AccountModels.csor AccountModels.vbwindow, press CTRL+M, CTRL+L.

    c.

    Scroll down and show the different regions of code.

    Note:The model code file contains the data structures for this web application and classes that

    control logic for working with the data store.

    d.

    In the AccountModels.csor AccountModels.vbwindow, click the Closebutton.

    7. View the Viewsfolder.

    In Solution Explorer, expand the Viewsfolder.

    Note:Several folders share their name with the names of the controllers in the Controllers

    folder.

    8.

    View the Views/Sharedfolder.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    19/180

    Overview of Web Application Architecture and Design 1-13

    In Solution Explorer, expand the Views/Sharedfolder.

    Note:The Sharedfolder contains master pages, user controls, and pages shared across the

    MVC web application.

    9.

    Close Microsoft Visual Studio 2010.

    In the DemoMvcApplication - Microsoft Visual Studio 2010window, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    20/180

    1-14 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 4

    Overview of the Request Life Cycle

    Contents:

    Question and Answers 15

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    21/180

    Overview of Web Application Architecture and Design 1-15

    Question and Answers

    Life Cycle of a Web Forms Request

    Question:What is postback data?

    Answers: Postback data is data that is available in the HTML form element.

    Life Cycle of an MVC Request

    Question:What is the first step of an MVC request?

    Answers: ASP.NET Routing routes the request to the appropriate resource.

    Comparison of the Web Forms and MVC Request Life Cycles

    Question:In what other ways do the request life cycles differ between Web Forms and MVC?

    Answer: May vary discuss with students.

    Working with the Web Forms Page Life Cycle

    Question:What other scenarios can you imagine where you would need to use events in the pages

    life cycle to process the page correctly?

    Answer: May vary discuss with students.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    22/180

    Designing a Web Application 2-1

    Module 2

    Designing a Web Application

    Contents:

    Lesson 1: Web Applications: Case Studies 2

    Lesson 2: Web Application Design Essentials 4

    Lesson 3: Visual Studio 2010 Tools and Technologiesfor Web Application Design 6

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    23/180

    2-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Web Applications: Case Studies

    Contents:

    Questions and Answers 3

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    24/180

    Designing a Web Application 2-3

    Questions and Answers

    Discussion: Overview of Web Applications and Their Characteristics

    Question:What are some further variations on websites that were not covered?

    Answer: Will vary.

    Question:While not being an exact fit, do these four types of websites relate to the previous

    questions answers in some ways?

    Answer: Will vary.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    25/180

    2-4 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 2

    Web Application Design Essentials

    Contents:

    Questions and Answers 5

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    26/180

    Designing a Web Application 2-5

    Questions and Answers

    Common Design Considerations

    Question:How does security play a role in every type of web application?

    Answer: Even for static websites, the file system should have security attached.

    Question: How do scalability and reliability relate to one another?

    Answer: Often scalability and reliability are closely linked, as the ability to recover from the loss of

    resources requires the ability of your web application to spread its processing across more than one

    single point of failure.

    Discussion: Web Forms and MVC

    Question:What features, common or different, do you see in both the Web Forms and MVC

    frameworks that would benefit your development efforts?

    Answer: May vary.

    Guidelines for Determining When to Use Web Forms and When to UseMVC

    Question:What solutions in your experience may have benefited from implementation using MVC?

    Answer: Will Vary.

    Question:What key features of Web Forms that you use frequently might you miss when developing

    with MVC?

    Answer: Will Vary.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    27/180

    2-6 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 3

    Visual Studio 2010 Tools and Technologies for WebApplication Design

    Contents:Questions and Answers 7

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    28/180

    Designing a Web Application 2-7

    Questions and Answers

    Overview of the Design View in Visual Studio 2010

    Question:What value does the Design view bring to your development process?

    Answer: The Design view shows you any master pages and nested master pages that are

    implemented in your page so that you see exactly what you would see when you view the page in a

    browser.

    Enterprise Library

    Question:What benefits can you see to using the Enterprise Library as a consistent interface for

    common tasks that your applications require?

    Answer: Will vary.

    IIS SEO ToolkitQuestion:What value do the robots.txtand sitemap.xmlfiles provide?

    Answer: The robots.txt file tells a search engine what it can and cannot crawl when indexing your

    site. The sitemap.xmlfile provides a map of your site for a search engine crawler. This allows the

    crawler to access areas of your site that it might not have without the sitemap.

    Question:How does the Site Analysis tool help you understand how a search engine crawler will

    react to the content of your site?

    Answer: By running the Site Analysis tool, you can find and correct potential issues that will stop a

    search engine crawler from properly attributing relevance to your content, and possibly halting theindexing of your site altogether.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    29/180

    Developing MVC Models 3-1

    Module 3

    Developing MVC Models

    Contents:

    Lesson 1: Exploring Ways to Create MVC Models 2

    Lesson 2: Working with Data in MVC Models 4

    Lesson 3: Creating a Data Repository 6

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    30/180

    3-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Exploring Ways to Create MVC Models

    Contents:

    Detailed Demo Steps 3

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    31/180

    Developing MVC Models 3-3

    Detailed Demo Steps

    Demonstration: Creating an MVC Model by Using Classes

    Creating an MVC model using classes

    Open Microsoft Visual Studio 2010.

    On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio

    2010, and then click Microsoft Visual Studio 2010.

    Create a new ASP.NET MVC 2 Web Applicationproject, with an associated Unit Test project.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click NewProject, or

    press CTRL+SHIFT+N.

    b.

    In the New Projectdialog box, in the left pane, click Visual C#or Visual Basic, in the middle

    pane, click ASP.NET MVC 2 Web Application, in the Locationbox, type D:\Demofiles\CSor

    D:\Demofiles\VB, and then click OK.

    c.

    In the Create Unit Test Projectdialog box, ensure the Yes, create a unit test projectcheck box

    is selected, and then click OK.Add a new class named Blogto the Modelsfolder.

    a.

    In Solution Explorer, right-click Models, point to Addand then click New Item, or press

    CTRL+SHIFT+A.

    b. In the Add New Item MvcApplication1dialog box, in the left pane, click Visual C#or Visual

    Basic, in the middle pane, click Class, in the Namebox, type Blog, and then click Add.

    Add the following code to the Blogclass.

    [Visual C#]

    public class Blog

    {

    public string Title { get; set; }public string Description { get; set; }

    }

    [Visual Basic]

    Public Class Blog

    Private Property Title As StringPrivate Property Description As String

    End Class

    Build the solution, and fix any errors.

    In the MvcApplication1 Microsoft Visual Studiowindow, on the Buildmenu, click Build

    Solution, or press CTRL+SHIFT+B.

    Close Visual Studio 2010.

    In the MvcApplication1 Microsoft Visual Studiowindow, click the Closebutton.

    Best Practices:Model should not be concerned about saving itself to the persistent medium,

    and the data access responsibility should be kept separate from the model.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    32/180

    3-4 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 2

    Working with Data in MVC Models

    Contents:

    Questions and Answers 5

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    33/180

    Developing MVC Models 3-5

    Questions and Answers

    Data Mapper Pattern

    Question:How is the Data Mapper pattern different from the Active Record pattern?

    Answer:The Active Record pattern uses a strongly typed class wrapper around a row in the database

    table, and thus directly mimics the database structure, while the Data Mapper pattern keeps the

    database structure and object structure separate.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    34/180

    3-6 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 3

    Creating a Data Repository

    Contents:

    Questions and Answers 7Detailed Demo Steps 8

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    35/180

    Developing MVC Models 3-7

    Questions and Answers

    Extending Model Classes to Add Business Rules

    Question:Why is it not a good idea to implement the business rules in the model class created by

    using the Entity Framework?

    Answer: When the project is built, custom code is overwritten.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    36/180

    3-8 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Creating a Data Repository

    This topic focuses on implementing a data repository. The demonstration uses the Entity Framework as

    the data model. The repository will exhibit persistenceand data retrievalmethods.

    1. Open Microsoft Visual Studio 2010.

    On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2.

    Open the MvcApplication1 solution at the following location.

    Programming Language Location

    Visual C# D:\Demofiles\CS\MvcApplication1

    Visual Basic D:\Demofiles\VB\MvcApplication1

    a.

    In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click OpenProject, or press CTRL+SHIFT+O.

    b.

    In the Open Projectdialog box, in the File namebox, type

    D:\Demofiles\CS\MvcApplication1\MvcApplication1.slnor

    D:\Demofiles\VB\MvcApplication1\MvcApplication1.slnand then click Open.

    3. Add a new ADO.NET Entity Data Model named MyModel.edmxto the project, and generate the

    model from database. The model must be added to the Modelsfolder.

    a. In Solution Explorer, right-click Models, point to Add, and then click New Item.

    b. In the Add New Item MvcApplication1 dialog box, in the left pane, click Data.

    c. In the middle pane, click ADO.NET Entity Data Model, in the Namebox, type

    MyModel.edmx, and then click Add.

    d.

    In the Entity Data Model Wizard, on the Choose Model Contentspage, click Generate

    from database, and then click Next.

    4.

    In the Entity Data Model Wizard, on the Choose Your Data Connectionpage, if the Which data

    connection should your application use to connect to the database?list, is empty, click New

    Connection, and create a new connection to the AdventureWorksLT2008R2database on the

    .\SQLExpressSQL Server instance.

    a. In the Choose Data Sourcedialog box, in the Data sourcelist, click Microsoft SQL

    Server, and then click OK.

    b.

    In the Connection Propertiesdialog box, in the Server namebox, type .\SQLExpress,

    in the Select or enter a database namelist, click AdventureWorksLT2008R2, and

    then click Continue.

    5. In the Entity Data Model Wizard, on the Choose Your Data Connectionpage, if the Which data

    connection should your application use to connect to the database?list, click 10264a-gen-

    dev\sqlexpress.AdventureWorksLT2008R2.Sales(LT), and then click Next.

    6.

    Select the Blogand Bloggertables from the database.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    37/180

    Developing MVC Models 3-9

    7.

    On the Choose Your Database Objectspage, in the Which database objects do you want to

    include in your modellist, expand Tables, select the Blogand Bloggercheck boxes, and then

    click Finish.

    8.

    Add a new data repository class named BlogRepositoryto the Modelsfolder.

    a.

    In Solution Explorer, right-click Models, point to Add, and then click New Item.

    b.

    In the Add New Item MvcApplication1 dialog box, in the left pane, click Visual C#or

    Visual Basic.

    c.

    In the middle pane, click Class, in the Namebox, type BlogRepository, and then click

    Add.

    9. Add the following code to the BlogRepositoryclass.

    [Visual C#]

    private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();public IQueryable GetAllBlogs()

    {

    return db.Blogs;

    }

    [Visual Basic]

    Private db As New AdventureWorksLT2008R2Entities()

    Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)Return db.Blogs

    End Function

    In the BlogRepository.csor BlogRepository.vbwindow, at the top of the

    BlogRepositoryclass, type the following code.

    [Visual C#]

    private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();public IQueryable GetAllBlogs()

    {

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    38/180

    3-10 Developing Web Applications with Microsoft Visual Studio 2010

    return db.Blogs;

    }

    [Visual Basic]

    Private AdventureWorksLT2008R2Entities db As New AdventureWorksLT2008R2Entities()

    Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)Return db.Blogs

    End Function

    10. Append the Savemethod to the BlogRepositoryclass, which is responsible for persisting the

    Blogobject into the database.

    [Visual C#]

    public static void Save(MvcApplication1.Models.Blog blog)

    {using (var db = new AdventureWorksLT2008R2Entities ())

    {

    if (blog.BloggerID == 0){

    db.AddToBlogs(blog);

    db.SaveChanges();}

    }

    }

    [Visual Basic]

    Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)Using db As New AdventureWorksLT2008R2Entities()

    If blog.BloggerID = 0 Then

    db.AddToBlogs(blog)db.SaveChanges()

    End If

    End UsingEnd Sub

    In the BlogRepository.csor BlogRepository.vbwindow, append the following code.

    [Visual C#]

    public static void Save(MvcApplication1.Models.Blog blog){

    using (var db = new AdventureWorksLT2008R2Entities ())

    {

    if (blog.BloggerID == 0){

    db.AddToBlogs(blog);

    db.SaveChanges();

    }}

    }

    [Visual Basic]

    Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)

    Using db As New AdventureWorksLT2008R2Entities()

    If blog.BloggerID = 0 Then

    db.AddToBlogs(blog)

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    39/180

    Developing MVC Models 3-11

    db.SaveChanges()

    End IfEnd Using

    End Sub

    11.

    Delete the Blogclass from the Modelsfolder.

    a.

    In Solution Explorer, in the Modelsfolder, right-click Blog.csor Blog.vb, and then clickDelete.

    b.

    In the Microsoft Visual Studiodialog box, click OK.

    12.

    Build the solution, and fix any errors.

    In the MvcApplication1 Microsoft Visual Studiowindow, on the Buildmenu, click

    Build Solution, or press CTRL+SHIFT+B.

    13. Close Visual Studio 2010.

    In the MvcApplication1 Microsoft Visual Studiowindow, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    40/180

    Developing MVC Controllers 4-1

    Module 4

    Developing MVC Controllers

    Contents:

    Lesson 1: Implementing MVC Controllers 2

    Lesson 2: Creating Action Methods 7

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    41/180

    4-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Implementing MVC Controllers

    Contents:

    Questions and Answers 3Detailed Demo Steps 4

    Additional Reading 6

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    42/180

    Developing MVC Controllers 4-3

    Questions and Answers

    What Is an MVC Controller?

    Question:What is the name of the Product controller class?

    Answer:Because each controller class must end with the Controller suffix, the name of the Product

    controller is ProductController.

    What Is an Action Filter?

    Question:What are some uses for action filters?

    Answer:The possible uses for action filters are as varied as the actions to which they can be applied.

    Some possible uses for action filters include:

    Logging, to track user interactions.

    "Anti-image-leeching," to prevent images from being loaded in pages that are not on your site. Web crawler filtering, to change application behavior based on the browser user agent.

    Localization, to set the locale.

    Dynamic actions, to inject an action into a controller.

    Question:What types of action filters does ASP.NET MVC provide?

    Answer:The types of action filters that ASP.NET MVC provides are:

    Authorization

    Action

    Result

    Exception

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    43/180

    4-4 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Creating an MVC Controller

    In this demonstration, you will learn how to create an MVC controller.

    1.

    Open Microsoft Visual Studio 2010. On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2. Create a new ASP.NET MVC 2 Web Applicationproject, with an associated Unit Test project.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click New

    Project, or press CTRL+SHIFT+N.

    b. In the New Projectdialog box, in the left pane, click Visual C#or Visual Basic, in the

    middle pane, click ASP.NET MVC 2 Web Application, in the Locationbox, type

    D:\Demofiles\CSor D:\Demofiles\VB, and then click OK.

    c.

    In the Create Unit Test Projectdialog box, ensure that Yes, create a unit test project

    is selected, and then click OK.

    3. Create a controller named BlogControllerin the Controllersfolder. The controller should

    include action methods for create, update, delete, and details scenarios.

    a.

    In Solution Explorer, right-click Controllers, point to Addand then click Controller.

    b. In the Add Controllerdialog box, in the Controller Namebox, type BlogController,

    select the Add action methods for Create, Update, Delete, and Details scenarios

    check box, and then click Add.

    4.

    Build the solution, and fix any errors.

    In the MvcApplication1 Microsoft Visual Studiowindow, on the Buildmenu, click

    Build Solution, or press CTRL+SHIFT+B.

    5.

    Close Visual Studio 2010.

    In the MvcApplication1 Microsoft Visual Studio window, click the Close button.

    Demonstration: Using an Action Filter

    In this demonstration, you will learn how to use a controller that is decorated with the

    HandleErrorAttributeattribute.

    1.

    Open Microsoft Visual Studio 2010.

    On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2.

    Open the MvcApplication1 solution from the following location.

    Programming Language Location

    Visual C# D:\Demofiles\CS\MvcApplication1

    Visual Basic D:\Demofiles\VB\MvcApplication1

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    44/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    45/180

    4-6 Developing Web Applications with Microsoft Visual Studio 2010

    Additional Reading

    What Is an MVC Controller?

    For more information about MVC controllers, see Controller Class.

    For more information about routing, see Understanding the MVC Application Execution

    Process.

    http://go.microsoft.com/fwlink/?LinkID=204023&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204025&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204025&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204025&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204025&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204023&clcid=0x409
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    46/180

    Developing MVC Controllers 4-7

    Lesson 2

    Creating Action Methods

    Contents:

    Questions and Answers 8Detailed Demo Steps 10

    Additional Reading 13

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    47/180

    4-8 Developing Web Applications with Microsoft Visual Studio 2010

    Questions and Answers

    What Are Action Methods?

    Question:What are the restrictions on action methods?

    Answer:Action methods:

    Must be public.

    Cannot be static.

    Cannot have unbounded generic type parameters.

    Cannot be overloaded based on parameters unless they are disambiguated with attributes

    such as NonActionAttributeor AcceptVerbsAttribute.

    Question:How do you prevent a public method of a controller from being treated like an action

    method?

    Answer:By default, ASP.NET MVC treats all public methods of a controller class as action methods. If

    your controller class contains a public method and you do not want it to be an action method, you

    must decorate that method with the NonActionAttributeattribute.

    Question:What is the shortest attribute you can use to designate that an action method should

    respond only to an HTTP Post?

    Answer:The shortest attribute you can use to designate that an action method should only respond

    to an HTTP Post is the HttpPostAttributeattribute.

    Calling an MVC View

    Question:Which types derive from the ActionResult class?

    Answer:The following types derive from ActionResultclass:

    ContentResult

    EmptyResult

    FileResult

    JavaScriptResult

    JsonResult

    PartialViewResult RedirectResult

    RedirectToRouteResult

    ViewResult

    Question:What are the three ways that the ViewResult class can pass data to the view?

    Answer:The three ways covered in this lesson are:

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    48/180

    Developing MVC Controllers 4-9

    ViewData

    TempData

    Viewproperty

    Retrieving Data from the Request

    Question:How can you retrieve data from a form?

    Answer:You can retrieve data by using the Requestobject, the model binders, and the

    FormCollection.

    Question:How can you access the list of errors that occurred during the model binding?

    Answer: The ModelState.Errorsproperty returns a ModelErrorCollectionobject that contains any

    errors that occurred during model binding.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    49/180

    4-10 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Retrieving Data from the Request

    In this demonstration, you will learn how to retrieve data from the RouteData, the QueryString, a TextBox,

    and the FormCollection.

    1. Open Microsoft Visual Studio 2010.

    On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2.

    Open the DemoHello solution from the following location.

    Programming Language Location

    Visual C# D:\Demofiles\CS

    Visual Basic D:\Demofiles\VB

    a.

    In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project,

    or press CTRL+SHIFT+O.

    b. In the Open Project dialog box, in the File name box, type

    D:\Demofiles\CS\DemoHello.sln or D:\Demofiles\VB\DemoHello.sln and then click Open.

    3.

    Retrieve data from the RouteData.

    a.

    Run the project by pressing CTRL+F5.

    b.

    In the Hello Page - Windows Internet Explorer window, click Hello.

    c.

    Append the following text to the URL in the address bar, and then press ENTER.

    /RouteDataDemo/World

    Note:The value of the id key, retrieved from the RouteData.Valueskey/value pair collection,(World) is displayed.

    d.

    Close Windows Internet Explorer.

    4.

    Retrieve data from the QueryString.

    a. Run the project by pressing CTRL+F5.

    b.

    In the Hello Page - Windows Internet Explorer window, click Hello.

    c.

    Append the following text to the URL in the address bar, and then press ENTER.

    /QueryStringDemo?id=World

    Note:The value of the id key, retrieved from the Request object key/value pair collection,(World) is displayed.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    50/180

    Developing MVC Controllers 4-11

    d.

    Close Internet Explorer.

    5.

    Retrieve data from the text box.

    a.

    Replace the content of the Content2 Content control in the Index.aspx page file in the

    Views\Hello folder with the following markup.

    [Visual C#]

    Enter Your Name:

    [Visual Basic]

    Enter Your Name:

    b.

    In Solution Explorer, click DemoHello.

    c.

    Run the project by pressing CTRL+F5.

    d. In the Hello Page - Windows Internet Explorer window, click Hello.

    e.

    Append the following text to the URL in the address bar, and then press ENTER.

    /TextBoxDemo

    f.

    In the Enter Your Name box, type your name, and then click Submit.

    Note:The value entered in the text box is displayed.

    g.

    Close Internet Explorer.

    6.

    Retrieve data from a FormCollection.

    a.

    Add a new action method named FormCollectionDemo in the HelloController.

    [Visual C#]

    public ActionResult FormCollectionDemo(FormCollection collection)

    {ViewData["Message"] = "Hello " + collection["id"];

    return View("Index");

    }

    [Visual Basic]

    Function FormCollectionDemo(ByVal collection As FormCollection) As ActionResult

    ViewData("Message") = "Hello " & collection("id")

    Return View("Index")

    End Function

    b. Run the project by pressing CTRL+F5.

    c.

    In the Hello Page- Windows Internet Explorer window, click Hello.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    51/180

    4-12 Developing Web Applications with Microsoft Visual Studio 2010

    d.

    Append the following text to the URL in the address bar, and then press ENTER.

    /FormCollectionDemo

    e.

    In the Enter Your Name box, type your name, and then click Submit.

    f.

    In the AutoComplete dialog box, click No.

    Note:The value entered in the text box, retrieved from the FormCollectionobject, is displayed.

    g.

    Close Internet Explorer.

    h.

    Close Visual Studio 2010.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    52/180

    Developing MVC Controllers 4-13

    Additional Reading

    Calling an MVC View

    For more information about the ActionResultclass, see ActionResult Class.

    For more information about the ViewResultclass, see ViewResult Class.

    http://go.microsoft.com/fwlink/?LinkID=204043&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204048&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204048&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204043&clcid=0x409
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    53/180

    Developing MVC Views 5-1

    Module 5

    Developing MVC Views

    Contents:

    Lesson 1: Implementing MVC Views 2

    Lesson 2: Implementing Strongly-Typed MVC Views 6

    Lesson 3: Implementing Partial MVC Views 13

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    54/180

    5-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Implementing MVC Views

    Contents:

    Questions and Answers 3Detailed Demo Steps 4

    Additional Reading 5

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    55/180

    Developing MVC Views 5-3

    Questions and Answers

    What Is an MVC View?

    Question:Where can the view associated with the Sampleaction method of the Homecontroller be

    located?

    Answer:The view associated with the Sample action method of the Home controller can be located

    in any of the following locations:

    ~/Views/Home/Sample.aspx

    ~/Views/Home/Sample.ascx

    ~/Views/Shared/Sample.aspx

    ~/Views/Shared/Sample.ascx

    Question:What is the difference between the ViewDataproperty and the TempDataproperty?

    Answer:The value of the TempDataproperty persists only from one request to the next.

    Question:What is the attribute of the Pagedirective that is used to identify the master page?

    Answer:The MasterPageFileattribute of the Pagedirective identifies the master page.

    What Are HTML Helpers?

    Question:What does an HTML helper return?

    Answer:An Html helper returns a string of type MvcHtmlString. An MvcHtmlStringrepresents an

    HTML-encoded string that should not be encoded again.

    Question:Into which categories are the HTML helpers organized?

    Answer:These are the categories that Html helpers are organized into:

    MvcForm Extensions

    Input Extensions

    Label Extensions

    Link Extensions

    Select Extensions

    TextArea Extensions

    Validation Extensions

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    56/180

    5-4 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Creating an MVC View

    In this demonstration, you will learn how to create an MVC view.

    1.

    Open Microsoft Visual Studio 2010. On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2. Create a new ASP.NET MVC 2 Web Applicationproject, without an associated Unit Test project.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click New

    Project, or press CTRL+SHIFT+N.

    b. In the New Projectdialog box, in the left pane, click Visual C#or Visual Basic, in the

    middle pane, click ASP.NET MVC 2 Web Application, in the Locationbox, type

    D:\Demofiles\CSor D:\Demofiles\VB, and then click OK.

    c.

    In the Create Unit Test Projectdialog box, ensure No, do not create a unit test

    projectis selected, and then click OK.

    3. Delete the Home\Aboutview.

    a.

    In Solution Explorer, expand Views, expand Home, right-click About.aspx, and then

    click Delete.

    b. In the Microsoft Visual Studiodialog box, click OK.

    4. Create an empty view named Aboutin the Homefolder.

    a.

    In Solution Explorer, right-click Home, point to Addand then click View.

    b. In the Add Viewdialog box, in the View namebox, type About, clear the Create a

    strongly-typed viewcheck box, and then click Add.

    5.

    Build the solution, and fix any errors.

    In the MvcApplication1 Microsoft Visual Studiowindow, on the Buildmenu, click

    Build Solution, or press CTRL+SHIFT+B.

    6.

    Run the application.

    a.

    In Solution Explorer, click MvcApplication1.

    b.

    In the MvcApplication1 Microsoft Visual Studiowindow, on the Debugmenu, click

    Start Without Debugging, or press CTRL+F5.

    c.

    In the Home Page Windows Internet Explorerwindow, click About.

    7.

    Close Windows Internet Explorer.

    In the About Windows Internet Explorerwindow, click the Closebutton.

    8.

    Close Visual Studio 2010.

    In the MvcApplication1 Microsoft Visual Studiowindow, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    57/180

    Developing MVC Views 5-5

    Additional Reading

    What Is an MVC View?

    For more information about the ViewPageclass, see ViewPage Class.

    For more information about the ViewDataDictionaryclass, see ViewDataDictionary Class.

    For more information about the TempDataDictionaryclass, see TempDataDictionary Class.

    What Are HTML Helpers?

    For more information about the HtmlHelperclass, see HtmlHelper Class.

    For more information about rendering a view using HTML helpers, see Rendering a Form inASP.NET MVC Using HTML Helpers.

    http://go.microsoft.com/fwlink/?LinkID=204060&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204061&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204062&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204063&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204064&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204064&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204064&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204064&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204063&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204062&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204061&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204060&clcid=0x409
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    58/180

    5-6 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 2

    Implementing Strongly-Typed MVC Views

    Contents:

    Questions and Answers 7Detailed Demo Steps 8

    Additional Reading 12

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    59/180

    Developing MVC Views 5-7

    Questions and Answers

    What Is a Strongly-typed View?

    Question:From which class does a strongly-typed view inherit?

    Answer:A strongly-type view inherits from ViewPage)

    Question:What is the easiest way to create a strongly-typed view?

    Answer:The easiest way to create a strongly-typed view is by using the Add View dialog box.

    Question:What are the advantages of using strongly-typed views?

    Answer:The advantages of using strongly-typed views are that the view knows exactly what type of

    data it is expecting and Microsoft IntelliSenseis available.

    http://msdn.microsoft.com/en-us/library/dd470798.aspxhttp://msdn.microsoft.com/en-us/library/dd470798.aspxhttp://msdn.microsoft.com/en-us/library/dd470798.aspxhttp://msdn.microsoft.com/en-us/library/dd470798.aspxhttp://msdn.microsoft.com/en-us/library/dd470798.aspxhttp://msdn.microsoft.com/en-us/library/dd470798.aspx
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    60/180

    5-8 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Creating a Strongly-typed View

    In this demonstration, you will see how to create a strongly-typed MVC view.

    1.

    Open Microsoft Visual Studio 2010. On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2. Create a new ASP.NET MVC 2 Web Applicationproject, without an associated Unit Test project.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click New

    Project, or press CTRL+SHIFT+N.

    b. In the New Projectdialog box, in the left pane, click Visual C#or Visual Basic, in the

    middle pane, click ASP.NET MVC 2 Web Application, in the Namebox, type

    StronglyTypedView, in the Locationbox, type D:\Demofiles\CSor D:\Demofiles\VB,

    and then click OK.

    c.

    In the Create Unit Test Projectdialog box, ensure No, do not create a unit test

    projectis selected, and then click OK.

    3. Add a model class named Personto the Modelsfolder.

    [Visual C#]

    using System.ComponentModel;

    using System.ComponentModel.DataAnnotations;

    public class Person

    {

    [Required]

    [DisplayName("First Name")]

    public string FirstName { get; set; }

    [Required]

    [DisplayName("Last Name")]

    public string LastName { get; set; }

    [Required]

    public int Age { get; set; }

    [Required]

    public string Gender { get; set; }

    }

    [Visual Basic]

    Imports System.ComponentModel

    Imports System.ComponentModel.DataAnnotations

    Public Class Person

    Public Property FirstName As String

    Public Property LastName As String

    Public Property Age As Integer

    Public Property Gender As String

    End Class

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    61/180

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    62/180

    5-10 Developing Web Applications with Microsoft Visual Studio 2010

    a.

    Replace the following markup and code.

    [Visual C#]

    model.Gender) %>

    [Visual Basic]

    b. With the following markup and code.

    [Visual C#]

    model.Gender,

    (SelectList)ViewData["Gender"]) %>

    [Visual Basic]

    7. Add an action method named Personto the HomeControllercontroller in the Controllers

    folder.

    [Visual C#]

    public ActionResult Person()

    {

    ViewData["Gender"] = new SelectList(new[] { "", "Female", "Male" });

    return View();

    }

    [Visual Basic]Public Function Person() As ActionResult

    ViewData("Gender") = New SelectList({"", "Female", "Male"})

    Return View()

    End Function

    a. In Solution Explorer, expand Controllers, and then double-click HomeController.

    b.

    In the HomeController.csor HomeController.vbwindow, in the HomeController

    class, type the following code.

    [Visual C#]

    public ActionResult Person()

    {ViewData["Gender"] = new SelectList(new[] { "", "Female", "Male" });

    return View();

    }

    [Visual Basic]

    Public Function Person() As ActionResult

    ViewData("Gender") = New SelectList({"", "Female", "Male"})

    Return View()

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    63/180

    Developing MVC Views 5-11

    End Function

    8.

    Run the application.

    a.

    In Solution Explorer, click StronglyTypedView.

    b.

    In the StronglyTypedView Microsoft Visual Studiowindow, on the Debugmenu,

    9.

    Navigate directly to the Personview, by using the following route.

    click Start Without Debugging, or press CTRL+F5.

    Home/Person

    In the Home Page Windows Internet Explorerwindow, in the address bar, append

    the following URL, and then press ENTER.

    Home/Person

    10. Close Internet Explorer.

    In thePerson Windows Internet Explorer

    window, click theClose

    button.

    11. Close Visual Studio 2010.

    In the StronglyTypedView Microsoft Visual Studiowindow, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    64/180

    5-12 Developing Web Applications with Microsoft Visual Studio 2010

    Additional Reading

    What Is a Strongly-typed View?

    For more information about the HtmlHelper(TModel) class, see HtmlHelper(TModel) Class.

    http://go.microsoft.com/fwlink/?LinkID=204065&clcid=0x409http://go.microsoft.com/fwlink/?LinkID=204065&clcid=0x409
  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    65/180

    Developing MVC Views 5-13

    Lesson 3

    Implementing Partial MVC Views

    Contents:

    Questions and Answers 14Detailed Demo Steps 15

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    66/180

    5-14 Developing Web Applications with Microsoft Visual Studio 2010

    Questions and Answers

    What Is a Partial View?

    Question:What is the HTML helper that is used to render a partial view?

    Answer: Html.RenderPartialis used to render a partial view.

    Question:In which type of file does a partial view store its markup?

    Answer: A partial view stores its markup in an ASP.NET user control (.ascx file).

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    67/180

    Developing MVC Views 5-15

    Detailed Demo Steps

    Demonstration: Creating a Partial MVC View

    In this demonstration, you will see how to create a partial MVC view.

    1.

    Open Microsoft Visual Studio 2010. On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual

    Studio 2010, and then click Microsoft Visual Studio 2010.

    2. Open the StronglyTypedViewsolution used in the previous demonstration.

    a. In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click Open

    Project, or press CTRL+SHIFT+O.

    b. In the Open Projectdialog box, in the File namebox, type

    D:\Demofiles\CS\StronglyTypedView\StronglyTypedView.slnor

    D:\Demofiles\VB\StronglyTypedView\StronglyTypedView.slnand then click Open.

    3.

    Add a strongly-typed partial view named Partialto the Views\Homefolder, by using the Add

    Viewdialog box. The view must contain default content for a Create view, and the view should

    be based on the Personclass.

    a. In Solution Explorer, expand Views, right-click Home, point to Add, and then click

    View.

    b. [Visual C#]In the Add Viewdialog box, in the View namebox, type Partial, select the

    Create a partial view (.ascx)and Create a strongly-typed viewcheck boxes, in the

    View data classlist, click Person, in the View contentlist, click Create, and then click

    Add.

    or-

    c. [Visual Basic]In the Add Viewdialog box, in the View namebox, type Partial, select

    the Create a partial view (.ascx)and Create a strongly-typed viewcheck boxes, in

    the View data classlist, click StronglyTypedView.Person, in the View contentlist,

    click Create, and then click Add.

    4.

    Add an empty view named Createto the Views\Homefolder, by using the Add Viewdialog

    box.

    a. In Solution Explorer, expand Views, right-click Home, point to Add, and then click

    View.

    b. In the Add Viewdialog box, in the View namebox, type Create, clear the Create a

    partial view (.ascx)and Create a strongly-typed viewcheck boxes, and then click

    Add.

    5.

    Incorporate the Partialview in the Createview as part of the Content2Contentcontrol, by

    using the Html.RenderPartialmethod.

    [Visual C#]

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    68/180

    5-16 Developing Web Applications with Microsoft Visual Studio 2010

    [Visual Basic]

    Add the following code to the Createview, in the Content2Contentcontrol,

    immediately after the h2element.

    [Visual C#]

    [Visual Basic]

    6. Run the application.

    a.

    In Solution Explorer, click StronglyTypedView.

    b.

    In the StronglyTypedView Microsoft Visual Studiowindow, on the Debugmenu,

    click Start Without Debugging, or press CTRL+F5.

    7. Navigate directly to the Personview, by using the following route.

    Home/Person

    In the Home Page Windows Internet Explorerwindow, in the address bar, append

    the following URL, and then press ENTER.

    Home/Person

    8. Close Internet Explorer.

    In the Person Windows Internet Explorerwindow, click the Closebutton.

    9.

    Close Visual Studio 2010.

    In the StronglyTypedView Microsoft Visual Studiowindow, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    69/180

    Designing for Discoverability 6-1

    Module 6

    Designing for Discoverability

    Contents:

    Lesson 1: Search Engine Optimization 2

    Lesson 2: Discoverability Files 7

    Lesson 3: Using ASP.NET Routing 12

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    70/180

    6-2 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 1

    Search Engine Optimization

    Contents:

    Questions and Answers 3Detailed Demo Steps 4

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    71/180

    Designing for Discoverability 6-3

    Questions and Answers

    Overview of Search Engine Optimization

    Question:When estimating the effort to complete a site, do you typically include SEO (search engine

    optimization) items?

    Answer: Will vary.

    Question:In which activities have you participated to increase a websites search ranking?

    Answer: Will vary.

    Question:How did traffic patterns change after you completed SEO activities?

    Answer: Will vary.

    Components of the IIS SEO ToolkitQuestion:Have you encountered a website that did not have an accurate robots.txtfile? What

    mistakes were made? Did traffic improve once the robots.txtfile was fixed?

    Answer: Will vary.

    Question:Have you encountered a website that did not have an accurate sitemap.xmlfile? If so,

    how did it impact your use and perception of the website?

    Answer: Will vary.

    Demonstration: Analyzing a Website by Using the IIS SEO Toolkit

    Question:When would be the ideal timeframe in a project to run the Site Analysis Tool?

    Answer: After initial development and after deployment.

    Question:What feature of the report can be used to avoid production issues proactively?

    Answer: Violations.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    72/180

    6-4 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Analyzing a Website by Using the IIS SEO Toolkit

    Detailed demonstration steps

    Crawling a Website

    1. Open IIS SEO Toolkit.

    a. On the Startmenu, point to All Programs, expand IIS 7.0 Extensions, right-click Search EngineOptimization (SEO) Toolkit 1.0, and then click Run as Administrator.

    b. In the User Account Controldialog box, in the Passwordbox, type Pa$$w0rd, and then clickYes.

    2. In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysissection, clickCreate a new analysis.

    3. In the New Analysisdialog box, in the Namebox, type Default Web Site analysis, in the Start URLbox, type http://localhost, and then click OK.

    Note:It is possible to crawl any website that is publicly accessible on the Internet.

    The New Analysis Dialog Box

    Advanced Settings

    Maximum Number of Links:Controls the number of unique links to be processed and downloaded

    from a website during a crawl. A link is any URL that is used within a pages markup, including hyperlinks,

    references to image files, CSS files, and java script files. Increasing this number increases the size of the

    reports file, and makes the crawling process run longer.

    Maximum Download Size per Link:Controls the number of kilobytes of content to be downloaded perlink. Increasing this number increases the size of the cached content stored by Site Analysis on the local

    file system.

    Ignore 'nofollow' attribute:The nofollowattribute and the nofollowmeta tag are used to tell search

    engine crawlers not to follow certain or all hyperlinks in the page. This is a means of protection against

    spam in blog comments. If pages on your site use this attribute, the hyperlinks on those pages will not be

    processed or analyzed during site analysis. However, links to resources such as images, CSS, and java script

    files will still be processed. If it is necessary to analyze the hyperlinks that use this attribute, use this setting

    to ignore the nofollowattributes and meta tags.

    Ignore 'noindex' meta tag:- Used to tell search engine crawlers not to index the content of the page. If

    pages on your site use this meta tag, the content of those pages will not be searched for any violations. If

    it is necessary to analyze even the pages that use this attribute, use this setting to ignore the noindexmeta tag.

    External Links:Use this drop-down list when your website has sub-domains, or when you want to run an

    analysis on a particular directory within a site. This setting controls whether sub-domains and/or

    subdirectories should be treated as external or internal links.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    73/180

    Designing for Discoverability 6-5

    Edit Feature Settings

    Maximum Number of Concurrent Requests:Controls the number of concurrent requests the web

    crawler will make.

    Reports Directory: Specifies the directory on the local file system where all crawled data and cached

    website content is stored.

    Note: Two numbers are reported during analysis.

    Links Processed:The total number of links that have been crawled and downloaded by theweb crawler.

    Total Links:The total number of links found while crawling the website.

    Interpreting the Site Analysis Report

    In Internet Information Services (IIS) Manager, in the Site Analysis Reportsection, you can view a

    number of pages with report details. To get to the Site Analysis Reportsection, follow these steps.

    1. Open IIS SEO Toolkit.

    a.

    On the Startmenu, point to All Programs, expand IIS 7.0 Extensions, right-click Search EngineOptimization (SEO) Toolkit, and then click Run as Administrator.

    b.

    In the User Account Controldialog box, in the Passwordbox, type Pa$$w0rd, and then clickYes.

    2.

    In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysissection, clickView existing reports.

    3.

    In the Site Analysispane, you can double-click any of the reports listed.

    Note:In the Site Analysis Reportsection, you can use the vertically placed tabs on the left of

    the Dashboard to get to the following information.

    Summary Page

    The site analysis summary page provides an overview of all SEO-related violations and problems found on

    the analyzed website. In addition, it contains a large set of pre-built reports about your site content and

    structure.

    You can drill down into each individual item in the report by double-clicking it, or by using the View

    Group Detailscommand in the context menu. To open a particular report in a separate query page, use

    the Open Querycontext menu command.

    Query Page

    Opening any of the pre-built reports from the summary page will result in a new query page.

    The query page is used to issue queries against the site analysis data that was collected during the crawl

    of the website. In the preceding screenshot, the query is used to get all the pages that reference images

    without specifying an altattribute within the imgHTML element.

    You can perform a set of actions, accessible from the context menu, for each item within the query results

    pane. The following actions are as follows:

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    74/180

    6-6 Developing Web Applications with Microsoft Visual Studio 2010

    View Details: This option opens a dialog box, which can be used to obtain detailed information about the

    item. Specifically, you can see the violation details and suggested corrective actions.

    In addition, the actual response data is available if you need to investigate the causes of the reported

    violation further. For example, if you want to find out where in the response HTML this violation occurred,

    choose the Contenttab. This opens the response content with the offending section of the markup

    highlighted.View in Browser: If you right-click a URL, you can select View in Browser from the context menu to show

    the URL in the browser.

    View Pages Linking to This Page: If you right-click a URL, you can also select View Pages Linking to

    This Page. This option opens a new query page that shows all the pages on the site that reference the

    URL for the selected item. This kind of report is useful when you want to find out which pages may be

    affected if you change a particular URL on your site.

    View Pages Linked by This Page: This option opens a new query page that shows all the URLs and

    resources that the HTML markup for the currently selected URL references.

    View Violations in This Page: This option opens a new query page that shows all the violations found on

    the page of the selected URL.View in Hierarchy: This option opens a hierarchy view page that consists of the following parts:

    URLs of all pages that lead to the selected page.

    The URL of the selected page.

    URLs of all the resources and pages referenced by the selected page.

    View Routes to this Page: This option opens a new page that displays the 5 shortest unique routes from

    the analysis start page to the currently selected page.

    Each route is shown with the start page at the bottom and each subsequent page above, with the selected

    page on top. This report can be used to analyze how visitors can get to a particular page on your website,

    and whether there any unnecessary pages that can be eliminated for users to discover the selected pagemore easily.

    Word Analysis: This feature can be used to get an idea of the most commonly used words in a pages

    content. These can be used as keywords for accurately describing the web page content for search

    engines.

    The most often used words within a page will be displayed, which can give you an idea of which keywords

    to choose for this page. In addition, the texts of links that reference this page are listed at the bottom of

    the dialog box. This helps you to check whether the anchor text used within those links accurately

    describes the content of the page.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    75/180

    Designing for Discoverability 6-7

    Lesson 2

    Discoverability Files

    Contents:

    Questions and Answers 8Detailed Demo Steps 9

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    76/180

    6-8 Developing Web Applications with Microsoft Visual Studio 2010

    Questions and Answers

    What are Robots Files?

    Question:Have you ever piloted or tested content in a production environment that you did not

    want a search engine to index?

    Answer: Will vary.

    Question:What are some disadvantages of allowing web crawlers to index content that is not ready

    for production?

    Answer:Search engines will pick up information that is not ready and direct users to it.

    What is the Sitemap File?

    Question:When do you usually install a sitemap file?

    Answer:At the start of a project.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    77/180

    Designing for Discoverability 6-9

    Detailed Demo Steps

    Demonstration: Creating a Robots File

    Detailed demonstration steps

    In this demonstration, you will see how to create a robots.txtfile.

    1. Open Internet Information Services (IIS) Manager as an administrator.

    a. On the Startmenu, click Control Panel.

    b.

    In Control Panel, click System and Security, and then click Administrative Tools.

    c. Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.

    2. In the User Account Controldialog box, in the Passwordbox, type Pa$$w0rd, and then pressENTER.

    3. Select the Default Website.

    In the Connectionspane, expand 10264A-GEN-DEV (10264A-GEN-DEV\Admin), expand

    Sites, and then click Default Web Site.4.

    Open the Search Engine Optimization feature.

    In Internet Information Services (IIS) Manager, in the middle pane, in the Managementsection,double-click Search Engine Optimization.

    5. View existing rules.

    In the Search Engine Optimizationpane, in the Robots Exclusionsection, click View existingrules.

    Note:Currently there are no rules, and there is no robots.txtfile.

    6.

    Add a sitemap file.a. In the Actionspane, in the Sitemap Locationssection, click Add Sitemaps.

    b.

    In the Add Sitemapsdialog box, in the URL Pathslist, select the Default Web Site, and thenclick OK.

    Note:Currently there are is no sitemap file, but this action will create the robots.txtfile.

    7. Open the robots.txtfile.

    In the Actionspane, in the Robotssection, click Open Robots.txt File.

    Note:The robots.txtfile is opened in Notepad. Currently, it holds only a reference to thesitemap at the default location for the default website.

    Following are examples of what you can add to a robots.txtfile.

    This example disallows all web spiders for the entire site:

    # Make changes for all web spiders

    User-agent: *

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    78/180

    6-10 Developing Web Applications with Microsoft Visual Studio 2010

    Disallow: /

    The following example disallows a robot named WebSpiderfrom the virtual paths/marketingand/sales:

    # Tell "WebSpider" where it can't go

    User-agent: WebSpider

    Disallow: /marketing

    Disallow: /sales

    # Allow all other robots to browse everywhere

    User-agent: *Disallow:

    This example allows only a web spider named SpiderOneinto a site, while denying all other spiders:

    # Allow "SpiderOne" in the site

    User-agent: SpiderOne

    Disallow:

    # Deny all other spiders

    User-agent: *Disallow: /

    This last example disallows FrontPage-related paths in the root of your website:

    # Ignore FrontPage files

    User-agent: *

    Disallow: /_borders

    Disallow: /_derivedDisallow: /_fpclass

    Disallow: /_overlay

    Disallow: /_privateDisallow: /_themes

    Disallow: /_vti_bin

    Disallow: /_vti_cnf

    Disallow: /_vti_logDisallow: /_vti_map

    Disallow: /_vti_pvtDisallow: /_vti_txt

    8.

    Close Notepad.

    In the robots.txt - Notepadwindow, click the Closebutton.

    9.

    Close Internet Information Services (IIS) Manager.

    In the Internet Information Services (IIS) Managerwindow, click the Closebutton.

    10.

    Close Administrative Tools.

    In the Control Panel\System and Security\Administrative Toolswindow, click the Closebutton.

    11. Close System and Security.

    In the Control Panel\System and Securitywindow, click the Closebutton.

    Demonstration: Creating a Sitemap File

    Detailed demonstration steps

    In this demonstration, you will see how to create a sitemap file by using the IIS SEO Toolkit extensions.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    79/180

    Designing for Discoverabili ty 6-11

    Creating a Sitemap File

    1.

    Open Internet Information Services (IIS) Manager as an administrator.

    On the Startmenu, click Control Panel.

    2.

    In Control Panel, click System and Security, and then click Administrative Tools.

    3.

    Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.4. In the User Account Controldialog box, in the Passwordbox, type Pa$$w0rd, and then press

    ENTER.

    5. Open the Search Engine Optimization feature.

    In the right pane, in the Management Groupsection, double-click Search EngineOptimization.

    6. Create a new sitemap for the default website, in a file named Sitemap.xml. Set the change frequencyto daily, do not record the last modified date and time, and set the priority to 1.

    a. In the Search Engine Optimizationpane, in the Sitemaps and Sitemap Indexessection, clickCreate a new sitemap.

    b.

    In the Choose Sitedialog box, in the Sitelist, click Default Web Site, and then click OK.

    c.

    In the Add Sitemapdialog box, in the File Namebox, type Sitemap.xml, and then click OK.

    d.

    In the Add URLsdialog box, in the URL Pathslist, click Default Web Site, and then click OK.

    7. Close Internet Information Services (IIS) Manager.

    In the Internet Information Services (IIS) Managerwindow, click the Closebutton.

    8.

    Close Administrative Tools.

    In the Control Panel\System and Security\Administrative Toolswindow, click the Closebutton.

    9. Close System and Security.

    In the Control Panel\System and Securitywindow, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    80/180

    6-12 Developing Web Applications with Microsoft Visual Studio 2010

    Lesson 3

    Using ASP.NET Routing

    Contents:

    Questions and Answers 13Detailed Demo Steps 14

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    81/180

    Designing for Discoverabili ty 6-13

    Questions and Answers

    How ASP.NET Routing Works

    Question:What are the advantages of using routed URLs over standard URLs?

    Answer: URLs are simpler and can be easily typed, copy-pasted, or used in search engines.

    Demonstration: Using ASP.NET Routing with Web Forms Pages

    Question:How can using ASP.NET Routing improve long-term maintenance of a web application?

    Answer: Changes to the website can be easily accomplished by updating the routing tables

    Question:What is your perception of a website when you get an HTTP 404 error?

    Answer: Will vary.

    Using ASP.NET Routing with MVC Pages

    Question:How does MVC built-in routing improve search engine query results?

    Answer:It produces search engine friendly URLs.

    Question:How does MVC built-in routing improve the maintainability of a website?

    Answer:It is simple to add or move views, by simply modifying the corresponding route.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    82/180

    6-14 Developing Web Applications with Microsoft Visual Studio 2010

    Detailed Demo Steps

    Demonstration: Using ASP.NET Routing with Web Forms Pages

    Detailed demonstration steps

    1.

    Open Microsoft Visual Studio 2010.

    On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.

    2. Open the WebFormsRouting solution at the following location.

    Programming Language Location

    Visual C# D:\Demofiles\CS

    Visual Basic D:\Demofiles\VB

    a.

    In the Start Page Microsoft Visual Studiowindow, on the Filemenu, click OpenProject, or

    press CTRL+SHIFT+O.b. In the Open Projectdialog box, in the File namebox, type

    D:\Demofiles\CS\WebFormsRouting.slnor D:\Demofiles\VB\WebFormsRouting.slnandthen click Open.

    3.

    Add reference to the System.Web.Routingassembly.

    a. In Solution Explorer, right-click WebFormsRouting, and then click Add Reference.

    b.

    In the Add Referencedialog box, click .NET.

    c.

    In the list, click System.Web.Routing, and then click OK.

    4. Open the Global.asaxfile.

    In Solution Explorer, double-click Global.asax.

    5.

    Import the System.Web.Routingnamespace in the Global.asaxcode file.

    At the top of the Global.asax.csor Global.asax.vbcode file, add the following code.

    [Visual C#]

    using System.Web.Routing;

    [Visual Basic]

    Imports System.Web.Routing

    6.

    Add a RegisterRoutesmethod as shown to the Globalclass.[Visual C#]

    void RegisterRoutes(RouteCollection routes)

    {

    routes.MapPageRoute(

    "SearchRoute", // Route name"search/{searchterm}", // URL with parameters

    "~/Search.aspx" // Web forms page to handle it

    );

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    83/180

    Designing for Discoverabili ty 6-15

    }

    [Visual Basic]

    Sub RegisterRoutes(ByVal routes As RouteCollection)

    ' Route name

    ' URL with parameters' Web forms page to handle it

    routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")

    End Sub

    In the Global.asax.csor Global.asax.vbwindow, in the Globalclass, add the following code.

    [Visual C#]

    void RegisterRoutes(RouteCollection routes)

    {

    routes.MapPageRoute("SearchRoute", // Route name

    "search/{searchterm}", // URL with parameters

    "~/Search.aspx" // Web forms page to handle it

    );}

    [Visual Basic]

    Private Sub RegisterRoutes(ByVal routes As RouteCollection)

    ' Route name

    ' URL with parameters' Web forms page to handle it

    routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")

    End Sub

    7.

    Modify the Application_Startmethod as shown.

    [Visual C#]

    void Application_Start()

    {

    RegisterRoutes(RouteTable.Routes);}

    [Visual Basic]

    Private Sub Application_Start()

    RegisterRoutes(RouteTable.Routes)

    End Sub

    8.

    Open the Search.aspx.csor Search.aspx.vbcode file.

    In Solution Explorer, right-click Search.aspx, and then click View Code.

    9. Modify the Page_Loadmethod in the Searchclass as shown.

    [Visual C#]

    protected void Page_Load(object sender, EventArgs e)

    {if (!Page.IsPostBack){

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    84/180

    6-16 Developing Web Applications with Microsoft Visual Studio 2010

    string searchTerm = "No Search Term specified.";

    if (RouteData.Values["searchterm"] != null)

    {searchTerm = "You searched for '" +

    RouteData.Values["searchterm"].ToString() + "'";

    }

    SearchTermLabel.Text = searchTerm;

    }}

    [Visual Basic]

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

    Dim searchTerm As String = "No Search Term specified."

    If Not RouteData.Values("searchterm") Is Nothing Then

    searchTerm = "You searched for '" &RouteData.Values("searchterm").ToString() & "'"

    End If

    SearchTermLabel.Text = searchTerm

    End If

    End Sub

    10.

    Run the application.

    a. In Solution Explorer, click WebFormsRouting.

    b.

    In the AdventureWorks Microsoft Visual Studiowindow, on the Debugmenu, click StartWithout Debugging, or press CTRL+F5.

    11. Navigate directly to the Searchpage by using the following route.

    search/My Search Term

    In the Home Page Windows Internet Explorerwindow, in the addressbar, append thefollowing text.

    search/My Search Term

    12.

    Close Windows Internet Explorer.

    In the http://localhost:xxxx/search/My%20Search%20Term Windows Internet Explorerwindow, click the Closebutton.

    13. Close Visual Studio 2010.

    In the RouteConstraints Microsoft Visual Studiowindow, click the Closebutton.

    Demonstration: Creating Custom Routes

    Detailed demonstration steps

    1. Open Microsoft Visual Studio 2010.

    On the Startmenu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio2010, and then click Microsoft Visual Studio 2010.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    85/180

    Designing for Discoverabili ty 6-17

    2.

    Create a new ASP.NET MVC 2 web application named Routesin the D:\Demofiles\CS\Module06orD:\Demofiles\VB\Module06folder, by using the ASP.NET MVC 2 Web Applicationtemplate.

    a.

    On the Filemenu, click New Project.

    b.

    In the Installed Templatessection, expand Visual Basicor Visual C#, and then click Web.

    c. In the list of project types, click ASP.NET MVC 2 Web Application.

    d.

    In the Namebox, type Routes.

    e.

    In the Locationbox, type D:\Demofiles\CS\Module06or D:\Demofiles\VB\Module06, andthen click OK.

    f.

    In the Create Unit Test Projectdialog box, select the No, do not create a unit test projectoption, and then click OK.

    3.

    Open the Global.asaxfile.

    In the Solution Explorer window, double-click Global.asax.

    4. Add the following route to the RegisterRoutesmethod as shown.

    [Visual C#]

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(

    "Address",

    "Address/{houseNumber}",new {controller="Address", action="List"}

    );

    [Visual Basic]

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    routes.MapRoute(

    "Address","Address/{houseNumber}",

    New With {.controller = "Address", .action = "List"} _)

    In the Global.asax.csor Global.asax.vbwindow, in the MvcApplicationclass, in theRegisterRoutesmethod, add the following code.

    [Visual C#]

    routes.MapRoute(

    "Address",

    "Address/{houseNumber}",new {controller="Address", action="List"}

    );

    [Visual Basic]

    routes.MapRoute(

    "Address","Address/{houseNumber}",

    New With {.controller = "Address", .action = "List"} _

    )

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    86/180

    6-18 Developing Web Applications with Microsoft Visual Studio 2010

    After this code:

    [Visual C#]

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    [Visual Basic]

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    5. Create the AddressControllercontroller.

    a.

    In the Solution Explorer window, right-click Controllers, point to Add, and then click Controller.

    b.

    In the Add Controllerdialog box, in the Controller Namebox, type AddressController, andthen click Add.

    6.

    Add the Listaction method to the AddressControllerclass as shown.

    [Visual C#]

    public ActionResult List(int houseNumber)

    {

    ViewData["HouseNumber"] = houseNumber.ToString();

    return View();

    }

    [Visual Basic]

    Function List(ByVal houseNumber As Integer) As ActionResult

    ViewData("HouseNumber") = houseNumber.ToString()

    Return View()End Function

    7.

    Create the Listview in the Views/Addressfolder.

    a. In the Solution Explorer window, right-click Views, point to Add, and then click New Folder.

    b.

    In the text box, type Address, and then press ENTER.

    c.

    In the Solution Explorer window, right-click Address, point to Add, and then click View.

    d. In the Add Viewdialog box, in the View namebox, type List, and then click Add.

    8.

    Replace the default content of the Content2Content control in the Listview with the followingmarkup and code, to display the house number requested.

    [Visual C#]

    List

    List of houses with number

    [Visual Basic]

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    87/180

    Designing for Discoverabili ty 6-19

    List

    List of houses with number

    9. Run the application.

    a.

    In Solution Explorer, click Routes.

    b.

    In the Routes Microsoft Visual Studiowindow, on the Debugmenu, click Start WithoutDebugging, or press CTRL+F5.

    10.

    Navigate directly to the Address/Listview by using the following route.

    Address/123

    In the Home Page Windows Internet Explorerwindow, in the address bar, append thefollowing text, and then press Enter.

    Address/123

    Note:A message stating List of houses with number 123is now shown.

    11.

    Navigate directly to the Address/Listview by using the following route.

    Address/twentyseven

    In the List Windows Internet Explorerwindow, in the address bar, replace Address/123withthe following text.

    Address/twentyseven

    Note:An error message is now shown.

    [Visual Basic]

    The parameters dictionary contains a null entry for parameter 'houseNumber' ofnon-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResultList(Int32)' in 'Routes.Routes.AddressController'. An optional parameter must be areference type, a nullable type, or be declared as an optional parameter.

    [Visual C#]

    The parameters dictionary contains a null entry for parameter 'houseNumber' ofnon-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResultList(Int32)' in 'Routes.Controllers.AddressController'. An optional parameter mustbe a reference type, a nullable type, or be declared as an optional parameter.

    12. Close Internet Explorer.

    In the window The parameters dictionary contains a null entry for parameter'houseNumber' of non-nullable type Windows Internet Explorer, click the Closebutton.

  • 8/9/2019 10264A Developing Web Applications with Microsoft Visual Studio 2010

    88/180

    6-20 Developing Web Applications with Microsoft Visual Studio 2010

    Keep the solution open for the next demonstration.

    Demonstration: Creating Route Constraints

    Detailed demonstration steps

    Use the solution from the previous demonstration.

    1. Modify the Addressroute in Global.asaxas shown to add an integer constraint to thehouseNumberparameter.

    [Visual C#]

    routes.MapRoute(

    "Address",

    "Address/{houseNumber}",

    new {controller="Address", action="List"},new {houseNumber= @"\d+"}

    );

    [Visual Basic]routes.MapRoute(

    "Address","Address/{houseNumber}",

    New With {.controller = "Address", .action = "List"}, _

    New With {.houseNumber = "\d+"} _)

    a. In the Routes Microsoft Visual Studiowindow, click Global.asax.csor Global.asax.vb.

    b.

    Insert the following code

    [Visual C#]

    ,

    new {houseNumber = @"\d+" }

    [Visual Basic]

    , _