Chapter 9: Creating Web Applications with ASP.NET MVC

269

This will create a new Controller with several methods for working with Customer data. Listing 9-1 already showed what a Controller looks like, and this is no different, except that it contains more action methods. The following sections explain how to perform various operations on customer data.

Displaying a Customer List

The first thing to do with customers is to display a list that will serve as a starting point for other operations. Listing 9-7 shows the Index action method of the CustomerController and how it gets a list of customers to display. The code uses the CustomerRepository, created in the preceding section. For C#, you need to add a using directive at the top of the file for the MyShopCS.Models namespace.

Listing 9-7 A Controller for displaying a list

C#:

public ActionResult Index()

{

var customers =

new CustomerRepository()

.GetCustomers();

return View(customers);

}

VB:

Function Index() As ActionResult

Dim custRep As New CustomerRepository

Dim customers As List(Of Customer)

customers = custRep.GetCustomers() Return View(customers)

End Function

Listing 9-7 shows how the Index method uses the CustomerRepository to get the list of customers. You need to pass that list to the View for display.

To create the View, right-click anywhere in the Index method and select Add View, which will display the Add View window, shown in Figure 9-5.

The name of the View is Index, corresponding to the name of the action method invoking the View. Naming the View after the action method is the default behavior, but

Page 292
Image 292
Microsoft 9GD00001 manual Displaying a Customer List, 269, Listing 9-7 a Controller for displaying a list