274Microsoft Visual Studio 2010: A Beginner’s Guide

As shown in Figure 9-6, the Customer tab appears first on the list, and clicking it shows the list of Customers. In addition to the content you see in the list, there are links, such as Edit and Create. The next section covers the Create operation.

Adding a New Customer

Creating a new customer involves presenting a screen for data entry and saving the new data when submitted. When creating a new object, your Controller needs two methods, a get method to initialize an empty Customer and a post method to save the new customer data. Listing 9-9 shows the get and post methods in the CustomerController class.

Listing 9-9 Creating a new Customer object

C#:

//

// GET: /Customer/Create

public ActionResult Create()

{

Customer cust = new Customer

{

Birthday = new DateTime(1980, 1, 1)

};

return View(cust);

}

//

// POST: /Customer/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(Customer cust)

{

try

{

if (string.IsNullOrEmpty(cust.Name))

{

ModelState.AddModelError( "Name", "Name is required."); return View();

}

Page 297
Image 297
Microsoft 9GD00001 manual Adding a New Customer, Listing 9-9 Creating a new Customer object