42
MCT USE ONLY. STUDENT USE PROHIBITED 'HYHORSLQJ MVC Models L3-29 Developing MVC Models Lab 3: Creating MVC Models Exercise 1: Exploring the AdventureWorks Database Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010 1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd. 2. 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. 3. Open the AdventureWorksMvc solution at the following location. Programming Language Location Visual C# ® D:\Lab Files\CS\Lab 03\Starter\Exercise 01 Visual Basic ® D:\Lab Files\VB\Lab 03\Starter\Exercise 01 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:\Lab Files\CS\Lab 03\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise 01\AdventureWorksMvc.sln and then click Open. Task 2: Open the AdventureWorks database Open the AdventureWorksLT2008R2 database by using Server Explorer. a. In the AdventureWorksMvc – Microsoft Visual Studio window, on the View menu, click Server Explorer, or press CTRL+ALT+S. b. In Server Explorer, right-click Data Connections, and then click Add Connection. c. In the Choose Data Source dialog box, in the Data source list, click SQL Server, and then click Continue.

MVC Models - Controllers

Embed Size (px)

Citation preview

Page 1: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-29

Developing MVC Models

Lab 3: Creating MVC Models

Exercise 1: Exploring the AdventureWorks Database

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.

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

3. Open the AdventureWorksMvc solution at the following location.

Programming Language Location

Visual C#® D:\Lab Files\CS\Lab 03\Starter\Exercise 01

Visual Basic® D:\Lab Files\VB\Lab 03\Starter\Exercise 01

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:\Lab Files\CS\Lab 03\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise 01\AdventureWorksMvc.sln and then click Open.

Task 2: Open the AdventureWorks database

• Open the AdventureWorksLT2008R2 database by using Server Explorer.

a. In the AdventureWorksMvc – Microsoft Visual Studio window, on the View menu, click Server Explorer, or press CTRL+ALT+S.

b. In Server Explorer, right-click Data Connections, and then click Add Connection.

c. In the Choose Data Source dialog box, in the Data source list, click SQL Server, and then click Continue.

Page 2: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-30 Lab 1: Exploring the Adventure Works Website

d. In the Add Connection dialog box, in the Server name box, type 10264A-GEN-DEV\SQLExpress, in the Select or enter a database name list, click AdventureWorksLT2008R2, and then click OK.

e. In Server Explorer, expand 10264a-gen-dev\sqlexpress.AdventureWorksLT2008R2.SalesLT.

Task 3: Examine the table schemas

1. Display the list of tables.

• In Server Explorer, expand Tables.

2. Open the Customer (SalesLT) table in the Table Designer.

• Right-click Customer (SalesLT), and then click Open Table Definition.

Page 3: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-31

3. Examine the schema of the table.

4. Close the Table Designer.

• In the SalesLT.Customer: Table(10264a-gen-dev\sqlexpress.AdventureWorksLT2008R2) window, click the Close button.

Task 4: Add relationships between tables using Diagrams

1. Create a new database diagram containing the Customer and CustomerAddress tables.

a. In Server Explorer, right-click Database Diagrams, and then click Add New Diagram.

b. In the Microsoft Visual Studio dialog box, click Yes.

c. In the Add Table dialog box, click Customer, press and hold down CTRL, click CustomerAddress, and then click Add.

d. Click Close.

Note: The relationship between the Customer and CustomerAddress table is one-to-many, which means that a single customer can have multiple addresses.

Page 4: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-32 Lab 1: Exploring the Adventure Works Website

2. Close the Database Designer and do not save the diagram.

a. In the 10264A-GEN-DEV\Student.Diagram1: Diagram(10264a-gev-dev\sqlexpress.AdventureWorksLT2008R2) window, click the Close button.

b. In the Microsoft Visual Studio dialog box, click No.

3. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 5: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-33

Exercise 2: Adding an ADO.NET Entity Data Model

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution at the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 02

Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 02

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:\Lab Files\CS\Lab 03\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise 02\AdventureWorksMvc.sln and then click Open.

Page 6: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-34 Lab 1: Exploring the Adventure Works Website

Task 2: Add Entity Data Model to the web application

1. Add a new ADO.NET Entity Data Model named AdventureWorks.edmx to the project, and then generate the model from database. The model must be added to the Models folder.

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

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

c. In the middle pane, click ADO.NET Entity Data Model, in the Name box, type AdventureWorks.edmx, and then click Add.

d. In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from database, and then click Next.

Page 7: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-35

2. Use the existing AdventureWorksLT2008ConnectionString connection string to connect to the database, and save the connection settings in the Web.config file as AdventureWorksEntities.

• On the Choose Your Data Connection page, in the Which data connection should your application use to connect to the database? list, click AdventureWorksLT2008ConnectionString (Settings), in the Save entity connection settings in Web.config as box, type AdventureWorksEntities, and then click Next.

Page 8: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-36 Lab 1: Exploring the Adventure Works Website

3. Select the Blog and Blogger tables from the database and name the model namespace AdventureWorksModel.

• On the Choose Your Database Objects page, in the Which database objects do you want to include in your model list, expand Tables, select the Blog and Blogger check boxes, in the Model Namespace box, type AdventureWorksModel, and then click Finish.

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

Page 9: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-37

Task 3: Add data repository

• Add a new data repository class named BlogRepository to the Models folder.

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

b. In the Add New Item – AdventureWorksMvc dialog box, in the left pane, click Visual C# or Visual Basic.

c. In the middle pane, click Class, in the Name box, type BlogRepository, and then click Add.

Task 4: Implement list, select, insert, update, and delete operations

1. Declare and instantiate a private AdventureWorksEntities object named db in the BlogRepository class.

[Visual C#]

private AdventureWorksEntities db = new AdventureWorksEntities();

[Visual Basic]

Private db As New AdventureWorksEntities

a. In the BlogRepository.cs or BlogRepository.vb window, at the top of the BlogRepository class, type the following code.

[Visual C#]

private AdventureWorksEntities db = new AdventureWorksEntities();

[Visual Basic]

Private db As New AdventureWorksEntities

2. Add the following method to the BlogRepository class to return a list of all of the blogs.

[Visual C#]

public IQueryable<Blog> GetAllBlogs() {

Page 10: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-38 Lab 1: Exploring the Adventure Works Website

return db.Blogs; }

[Visual Basic]

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

3. Add the following method to the BlogRepository class to return a list of all of the blogs for a specific blogger.

[Visual C#]

public IQueryable<Blog> GetAllBlogs(int id) { return from blog in db.Blogs where blog.BloggerID == id select blog; }

[Visual Basic]

Public Function GetAllBlogs(ByVal id As Integer) As IQueryable(Of Blog) Return From blog In db.Blogs Where blog.BloggerID = id Select blog End Function

4. Add the following method to the BlogRepository class to return a specific blog.

[Visual C#]

public Blog GetBlog(int id) { return (from blog in db.Blogs where blog.BlogID == id select blog).SingleOrDefault(); }

Page 11: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-39

[Visual Basic]

Public Function GetBlog(ByVal id As Integer) As Blog Return (From blog In db.Blogs Where blog.BlogID = id Select blog).SingleOrDefault() End Function

5. Add the following method to the BlogRepository class to return the name of the blogger.

[Visual C#]

public string GetBloggerName(int id) { var bloggerName = (from blogger in db.Bloggers where blogger.BloggerID == id select blogger.Name).FirstOrDefault(); return bloggerName; }

[Visual Basic]

Public Function GetBloggerName(ByVal id As Integer) As String Dim bloggerName = (From blogger In db.Bloggers Where blogger.BloggerID = id Select blogger.Name).FirstOrDefault Return bloggerName End Function

6. Add the following methods to the BlogRepository class to add, update, delete, and save individual blogs.

[Visual C#]

public void AddBlog(Blog blog) { db.Blogs.AddObject(blog); } public void UpdateBlog(Blog blog) { db.Blogs.ApplyCurrentValues(blog); }

Page 12: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-40 Lab 1: Exploring the Adventure Works Website

public void DeleteBlog(Blog blog) { db.Blogs.DeleteObject(blog); } public void Save() { db.SaveChanges(); }

[Visual Basic]

Public Sub AddBlog(ByVal blg As Blog) db.Blogs.AddObject(blg) End Sub Public Sub UpdateBlog(ByVal blg As Blog) db.Blogs.ApplyCurrentValues(blg) End Sub Public Sub DeleteBlog(ByVal blg As Blog) db.Blogs.DeleteObject(blg) End Sub Public Sub Save() db.SaveChanges() End Sub

7. Save all modified files.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the File menu, click Save All, or press CTRL+SHIFT+S.

8. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 13: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-41

Exercise 3: Model Data Validation

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution at the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 03\Starter\Exercise 03

Visual Basic D:\Lab Files\VB\Lab 03\Starter\Exercise 03

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:\Lab Files\CS\Lab 03\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 03\Starter\Exercise 03\AdventureWorksMvc.sln and then click Open.

Task 1: Add a partial class to the Models folder

1. Add a new class named Blog to the Models folder.

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

b. In the Add New Item – AdventureWorksMvc dialog box, in the left pane, click Visual C# or Visual Basic.

c. In the middle pane, click Class, in the Name box, type Blog, and then click Add.

2. Make the Blog class partial, by prefixing with the keyword partial/Partial.

[Visual C#]

public partial class Blog

Page 14: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-42 Lab 1: Exploring the Adventure Works Website

[Visual Basic]

Partial Public Class Blog

3. Import the System.ComponentModel and System.ComponentModel.DataAnnotations namespaces.

[Visual C#]

using System.ComponentModel.DataAnnotations; using System.ComponentModel;

[Visual Basic]

Imports System.ComponentModel.DataAnnotations Imports System.ComponentModel

a. In the Blog.cs or Blog.vb window, add the following code at the top.

[Visual C#]

using System.ComponentModel.DataAnnotations; using System.ComponentModel;

[Visual Basic]

Imports System.ComponentModel.DataAnnotations Imports System.ComponentModel

Task 3: Add business rules validation

1. Add another class named BlogMetadata to the Blog.cs or Blog.vb code file.

[Visual C#]

public class Blog_MetaData { [DisplayName("Blog ID")] public object BlogID { get; set; } [DisplayName("Date Posted")] [DisplayFormat(DataFormatString = "{0:d}")] public object DatePosted { get; set; }

Page 15: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-43

[Required] public object Title { get; set; } [Required] [DisplayName("Blog Entry")] public object BlogEntry { get; set; } }

[Visual Basic]

Public Class Blog_MetaData <DisplayName("Blog ID")> Public Property BlogID As Object <DisplayName("Date Posted")> <DisplayFormat(DataFormatString:="{0:d}")> Public Property DatePosted As Object <Required()> Public Property Title As Object <Required()> <DisplayName("Blog Entry")> Public Property BlogEntry As Object End Class

• In the Blog.cs or Blog.vb window, add the following code at the bottom.

[Visual C#]

public class Blog_MetaData { [DisplayName("Blog ID")] public object BlogID { get; set; } [DisplayName("Date Posted")] [DisplayFormat(DataFormatString = "{0:d}")] public object DatePosted { get; set; } [Required] public object Title { get; set; } [Required] [DisplayName("Blog Entry")] public object BlogEntry { get; set; } }

Page 16: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L3-44 Lab 1: Exploring the Adventure Works Website

[Visual Basic]

Public Class Blog_MetaData <DisplayName("Blog ID")> Public Property BlogID As Object <DisplayName("Date Posted")> <DisplayFormat(DataFormatString:="{0:d}")> Public Property DatePosted As Object <Required()> Public Property Title As Object <Required()> <DisplayName("Blog Entry")> Public Property BlogEntry As Object End Class

2. Apply the MetadataType attribute to the Blog class, and reference the Blog_Metadata type as the metadata type.

[Visual C#]

[MetadataType(typeof(Blog_MetaData))] public partial class Blog

[Visual Basic]

<MetadataType(GetType(Blog_MetaData))> Partial Public Class Blog

• In the Blog.cs or Blog.vb window, add the following above the class declaration.

[Visual C#]

[MetadataType(typeof(Blog_MetaData))] public partial class Blog

[Visual Basic]

<MetadataType(GetType(Blog_MetaData))> Partial Public Class Blog

Page 17: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

MVC Models L3-45

3. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

4. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Task 4: Turn off the virtual machine and revert the changes

1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off.

2. In the Turn Off Machine dialog box, click Turn Off.

3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

4. In the Revert Virtual Machine dialog box, click Revert.

Page 18: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Page 19: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-47

Developing MVC Controllers

Lab 4: Developing MVC Controllers

Exercise 1: Creating an MVC Controller

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

1. Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.

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

3. Open the AdventureWorksMvc solution from the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 01

Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 01

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:\Lab Files\CS\Lab 04\Starter\Exercise 01\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise 01\AdventureWorksMvc.sln and then click Open.

Task 2: Create a controller named BlogController

1. Create a controller named BlogController in the Controllers folder. The controller should not include action methods for create, update, delete, and details scenarios.

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

b. In the Add Controller dialog box, in the Controller Name box, type BlogController, and then click Add.

Page 20: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-48 Lab 4: Developing MVC Controllers

2. Add the HandleErrorAttribute attribute to the BlogController class.

[Visual C#] [HandleError]

[Visual Basic] <HandleError()>

• Annotate the BlogController with the following attribute.

[Visual C#] [HandleError]

[Visual Basic] <HandleError()>

3. Verify that the code in the BlogController code file matches the following code.

[Visual C#] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AdventureWorksMvc.Controllers { [HandleError] public class BlogController : Controller { // // GET: /Blog/ public ActionResult Index() { return View(); } } }

Page 21: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-49

[Visual Basic] Namespace AdventureWorksMvc <HandleError()> Public Class BlogController Inherits System.Web.Mvc.Controller ' ' GET: /Blog Function Index() As ActionResult Return View() End Function End Class End Namespace

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 22: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-50 Lab 4: Developing MVC Controllers

Exercise 2: Adding code to list the existing blog entries

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution from the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 02

Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 02

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:\Lab Files\CS\Lab 04\Starter\Exercise 02\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise 02\AdventureWorksMvc.sln and then click Open.

Task 2: Add a blogRepository object

1. Import the AdventureWorksMvc.Models namespace in the BlogController code file.

[Visual C#] using AdventureWorksMvc.Models;

[Visual Basic] Not applicable

a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or BlogController.vb.

b. In the BlogController code file, insert the following code at the top of the file.

[Visual C#]

Page 23: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-51

using AdventureWorksMvc.Models;

[Visual Basic] Not applicable

2. Declare and instantiate a private BlogRepository object at the top of the BlogController class.

[Visual C#] private BlogRepository blogRepository = new BlogRepository();

[Visual Basic] Private blogRepository As New BlogRepository()

Task 3: Add code to the Index action method

1. Replace the existing code in the Index action method with code that returns all of the blog entries to the view, by calling the GetAllBlogs method of the blogRepository object.

[Visual C#] var blogs = blogRepository.GetAllBlogs(); return View(blogs);

[Visual Basic] Dim blogs = blogRepository.GetAllBlogs() Return View(blogs)

2. Verify that the final Index action method matches the following code:

[Visual C#] public ActionResult Index() { var blogs = blogRepository.GetAllBlogs(); return View(blogs); } [Visual Basic] Function Index() As ActionResult

Page 24: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-52 Lab 4: Developing MVC Controllers

Dim blogs = blogRepository.GetAllBlogs() Return View(blogs) End Function

Task 4: Create a Blogger action method

1. Add a Blogger action method that takes the ID of the blogger as the only parameter.

[Visual C#] public ActionResult Blogger(int id) { }

[Visual Basic] Function Blogger(ByVal id As Integer) As ActionResult End Function

2. Add code to the Blogger action method to return only the blog entries for the indicated blogger to the view.

[Visual C#] var blogs = blogRepository.GetAllBlogs(id); return View(blogs);

[Visual Basic] Dim blogs = blogRepository.GetAllBlogs(id) Return View(blogs)

3. Verify that the final Blogger action method matches the following code.

[Visual C#] public ActionResult Blogger(int id) { var blogs = blogRepository.GetAllBlogs(id); return View(blogs); }

Page 25: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-53

[Visual Basic] Function Blogger(ByVal id As Integer) As ActionResult Dim blogs = blogRepository.GetAllBlogs(id) Return View(blogs) End Function

Task 5: Create a Details action method

1. Add a Details action method that takes the ID of the blog entry as its one parameter.

[Visual C#] public ActionResult Details(int id) { }

[Visual Basic] Function Details(ByVal id As Integer) As ActionResult End Function

2. Add code to the Details action method to return only the indicated blog entry, to the view. However, if the blog entry no longer exists, redirect the user to the Index view.

[Visual C#] var blogEntry = blogRepository.GetBlog(id); if (blogEntry == null) return RedirectToAction("Index"); return View(blogEntry);

[Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

Page 26: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-54 Lab 4: Developing MVC Controllers

3. Verify that the final Details action method matches the following code.

[Visual C#] public ActionResult Details(int id) { var blogEntry = blogRepository.GetBlog(id); if (blogEntry == null) return RedirectToAction("Index"); return View(blogEntry); }

[Visual Basic] Function Details(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 27: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-55

Exercise 3: Adding code to create a new blog entry

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution from the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 03

Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 03

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:\Lab Files\CS\Lab 04\Starter\Exercise 03\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise 03\AdventureWorksMvc.sln and then click Open.

Task 2: Create a Create action method

1. Add a Create action method in the BlogController class.

[Visual C#] public ActionResult Create() { }

[Visual Basic] Function Create() As ActionResult End Function

a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or BlogController.vb.

b. In the BlogController code file, add the following method to the BlogController class.

Page 28: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-56 Lab 4: Developing MVC Controllers

[Visual C#] public ActionResult Create() { }

[Visual Basic] Function Create() As ActionResult End Function

2. Add code to the Create action method to return an empty ActionResult, to the view.

[Visual C#] return View();

[Visual Basic] Return View()

3. Verify that the final Create action method matches the following code:

[Visual C#] public ActionResult Create() { return View(); }

[Visual Basic] Function Create() As ActionResult Return View() End Function

Page 29: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-57

Task 3: Create a Create action method for an HTTP Post request

1. Add a Create action method for an HTTP Post request that takes a Blog object as the only parameter.

[Visual C#] [HttpPost] public ActionResult Create(Blog blog) { }

[Visual Basic] <HttpPost()> Function Create(ByVal blg As Blog) As ActionResult End Function

2. Add code to the Create action method to save the new Blog object and redirect the user to the Index view. However, if the call to the Save method fails, return the user to the Create view.

[Visual C#] if (!ModelState.IsValid) return View(blog); try { blog.DatePosted = DateTime.Now; blogRepository.AddBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been added."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); };

[Visual Basic] If ModelState.IsValid Then Try blg.DatePosted = DateTime.Now blogRepository.AddBlog(blg)

Page 30: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-58 Lab 4: Developing MVC Controllers

blogRepository.Save() TempData("ConfirmationMessage") = blg.Title & " has been added" Return RedirectToAction("Index") Catch Return View(blg) End Try End If Return View(blg)

3. Verify that the final Create action method that for the HTTP Post request matches the following code.

[Visual C#] [HttpPost] public ActionResult Create(Blog blog) { if (!ModelState.IsValid) return View(blog); try { blog.DatePosted = DateTime.Now; blogRepository.AddBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been added."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); }; }

[Visual Basic] <HttpPost()> Function Create(ByVal blg As Blog) As ActionResult If ModelState.IsValid Then Try blg.DatePosted = DateTime.Now blogRepository.AddBlog(blg)

Page 31: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-59

blogRepository.Save() TempData("ConfirmationMessage") = blg.Title & " has been added" Return RedirectToAction("Index") Catch Return View(blg) End Try End If Return View(blg) End Function

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 32: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-60 Lab 4: Developing MVC Controllers

Exercise 4: Adding code to edit a blog entry

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution from the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 04\Starter\Exercise 04

Visual Basic D:\Lab Files\VB\Lab 04\Starter\Exercise 04

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:\Lab Files\CS\Lab 04\Starter\Exercise 04\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise 04\AdventureWorksMvc.sln and then click Open.

Task 2: Create an Edit action method

1. Add an Edit action method that takes the ID of a blog entry as the only parameter. The method should be added to the BlogController class.

[Visual C#] public ActionResult Edit(int id) { }

[Visual Basic] Function Edit(ByVal id As Integer) As ActionResult End Function

Page 33: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-61

a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or BlogController.vb.

b. In the BlogController code file, add the following method to the BlogController class.

[Visual C#] public ActionResult Edit(int id) { }

[Visual Basic] Function Edit(ByVal id As Integer) As ActionResult End Function

2. Add code to the Edit action method to return the indicated Blog entry, to the view. However, if the blog entry no longer exists, redirect the user to the Index view.

[Visual C#] var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); return View(blog);

[Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

3. Verify that the final Edit action method matches the following code.

[Visual C#] public ActionResult Edit(int id) { var blog = blogRepository.GetBlog(id); if (blog == null)

Page 34: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-62 Lab 4: Developing MVC Controllers

return RedirectToAction("Index"); return View(blog); } [Visual Basic] Function Edit(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

Task 3: Create an Edit action method for an HTTP Post request

1. Add an Edit action method for an HTTP Post request that takes the ID of the blog entry and the FormCollection as the two parameters.

[Visual C#] [HttpPost] public ActionResult Edit(int id, FormCollection collection) { }

[Visual Basic] <HttpPost()> Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult End Function

2. Add code to the Edit action method to save the blog entry and redirect the user to the Index view. However, if the call to the Save method fails, return the user to the Edit view. Also, if the blog entry no longer exists, redirect the user to the Index view.

[Visual C#] var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); try {

Page 35: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-63

UpdateModel(blog, collection.ToValueProvider()); blogRepository.UpdateBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been updated."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); };

[Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Try UpdateModel(blogEntry, collection.ToValueProvider()) blogRepository.UpdateBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been updated" Return RedirectToAction("Index") Catch Return View(blogEntry) End Try

3. Verify that the final Edit action method for an HTTP Post request matches the following code.

[Visual C#] [HttpPost] public ActionResult Edit(int id, FormCollection collection) { var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); try

Page 36: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-64 Lab 4: Developing MVC Controllers

{ UpdateModel(blog, collection.ToValueProvider()); blogRepository.UpdateBlog(blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been updated."; return RedirectToAction("Index"); } catch (Exception) { return View(blog); }; }

[Visual Basic] <HttpPost()> Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Try UpdateModel(blogEntry, collection.ToValueProvider()) blogRepository.UpdateBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been updated" Return RedirectToAction("Index") Catch Return View(blogEntry) End Try End Function

Page 37: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-65

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Page 38: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-66 Lab 4: Developing MVC Controllers

Exercise 5: Adding code to delete a blog entry

Task 1: Open the AdventureWorksMvc solution in Visual Studio 2010

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 AdventureWorksMvc solution from the following location.

Programming Language Location

Visual C# D:\Lab Files\CS\Lab 05\Starter\Exercise 03

Visual Basic D:\Lab Files\VB\Lab 05\Starter\Exercise 03

In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project, or press CTRL+SHIFT+O.

In the Open Project dialog box, in the File name box, type D:\Lab Files\CS\Lab 04\Starter\Exercise 05\AdventureWorksMvc.sln or D:\Lab Files\VB\Lab 04\Starter\Exercise 05\AdventureWorksMvc.sln and then click Open.

Task 2: Create a Delete action method

1. Add a Delete action method that takes the ID of a blog entry as the only parameter. The method should be added to the BlogController class.

[Visual C#] public ActionResult Delete(int id) { }

[Visual Basic] Function Delete(ByVal id As Integer) As ActionResult End Function

a. In Solution Explorer, expand Controllers, and then double-click BlogController.cs or BlogController.vb.

b. In the BlogController code file, add the following method to the BlogController class.

Page 39: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-67

[Visual C#] public ActionResult Delete(int id) { }

[Visual Basic] Function Delete(ByVal id As Integer) As ActionResult End Function

2. Add code to the Delete action method to redirect to the Index view.

[Visual C#] var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); return View(blog);

[Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry)

3. Verify that the final Delete action method matches the following code.

[Visual C#] public ActionResult Delete(int id) { var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); return View(blog); }

[Visual Basic]

Page 40: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-68 Lab 4: Developing MVC Controllers

Function Delete(ByVal id As Integer) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If Return View(blogEntry) End Function

Task 3: Create a Delete action method for an HTTP Post request

1. Add a Delete action method for an HTTP Post request that takes the ID of the blog entry and a confirmation string as the two parameters.

[Visual C#] [HttpPost] public ActionResult Delete(int id, string confirmation) { }

[Visual Basic] <HttpPost()> Function Delete(ByVal id As Integer, ByVal confirmation As String) As ActionResult End Function

2. Add code to the Delete action method to delete the blog entry and redirect the user to the Index view.

[Visual C#] var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); blogRepository.DeleteBlog((Blog) blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been deleted."; return RedirectToAction("Index");

Page 41: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

Module 4: Developing MVC Controllers L4-69

[Visual Basic] Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If blogRepository.DeleteBlog(CType(blogEntry, Blog)) blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted." Return RedirectToAction("Index")

3. Verify that the final Delete action method for an HTTP Post request matches the following code.

[Visual C#] [HttpPost] public ActionResult Delete(int id, string confirmation) { var blog = blogRepository.GetBlog(id); if (blog == null) return RedirectToAction("Index"); blogRepository.DeleteBlog((Blog) blog); blogRepository.Save(); TempData["ConfirmationMessage"] = blog.Title + " has been deleted."; return RedirectToAction("Index"); }

[Visual Basic] <HttpPost()> Function Delete(ByVal id As Integer, ByVal confirmation As String) As ActionResult Dim blogEntry = blogRepository.GetBlog(id) If blogEntry Is Nothing Then Return RedirectToAction("Index") End If blogRepository.DeleteBlog(CType(blogEntry, Blog))

Page 42: MVC Models - Controllers

MC

T USE O

NLY. STU

DEN

T USE PR

OH

IBITED

L4-70 Lab 4: Developing MVC Controllers

blogRepository.Save() TempData("ConfirmationMessage") = blogEntry.Title & " has been deleted." Return RedirectToAction("Index") End Function

4. Build the solution, and fix any errors.

• In the AdventureWorksMvc – Microsoft Visual Studio window, on the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5. Close Visual Studio 2010.

• In the AdventureWorksMvc – Microsoft Visual Studio window, click the Close button.

Task 4: Turn off the virtual machine and revert the changes

1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off.

2. In the Turn Off Machine dialog box, click Turn Off.

3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

4. In the Revert Virtual Machine dialog box, click Revert.