249 Chapter 9 Creating Web Applications with ASP.NET MVC 250 Microsoft Visual Studio 2010: A Beginner’s Guide Key Skills & Concepts ● Learn What MVC Means ● Create Models ● Create Controllers ● Create Views ● Work with Data in ASP.NET MVC A SP.NET is a .NET technology for building Web applications. VS provides support for building a Web application through windows such as the Toolbox, Designer, and Properties windows, as well as the Solution Explorer. This chapter shows you how to use ASP.NET MVC. MVC is an acronym for Model View Controller, which is a well-known design pattern for building applications. You’ll learn about how MVC works and how it is implemented in ASP.NET MVC. Let’s start by helping you understand what MVC is. Understanding ASP.NET MVC The essential piece of knowledge required to be successful with ASP.NET MVC is the Model View Controller pattern. In MVC, the Model, View, and Controller are three separate objects. Table 9-1 describes the purpose of each MVC object. With MVC, you have a clear separation of concerns where Model, View, and Controller have distinct responsibilities. This makes it easier to write good programs that you can return to later for fixing bugs and adding new features. Besides knowing what each of these three objects is, you must understand their relationship. Figure 9-1 illustrates the Model, the Table 9-1 Purpose of MVC Objects MVC Object Purpose Model The Model is made up of business objects and data. View Each MVC application typically has a user interface that displays information to a user and allows the user to input data. The data that the View displays is read from a Model, and the data that the user adds to the View is assigned to the Model. Controller A Controller orchestrates the activities of an application. When a user makes a request for your application, ASP.NET MVC invokes a Controller. The Controller will communicate with the Model and View to ensure the program operates correctly. Chapter 9: Creating Web Applications with ASP.NET MVC 251 View, and the Controller, including relationships. There are variations of the relationship between Model, View, and Controller, so rather than a theoretically correct depiction of all scenarios, Figure 9-1 is a simplification that should help you get started. In Figure 9-1, you can see that the Controller references both the V iew and the Model. This makes sense when you consider that the Controller is managing the operation of the application. The Controller executes in response to a user request. Since the Controller is also responsible for coordinating activity between the Model and the V iew, you can see the relationship in Figure 9-1 where the Controller references the Model. The View references the Model because the View must bind data to the user interface and needs to know what data is available. The Model does not reference the View or the Controller. The Model is an object that holds data and any other members that help manage that data, such as methods for performing validation. A typical sequence of operations for an ASP.NET MVC operation starts with a request to a Controller. The Controller will perform the actions requested, working with the Model. The Controller will then give the Model to a View and run the View. The View will display Model data and interact with the user for any screen operations. Based on user interaction with the View, more requests will be made to a Controller to repeat this process. The rest of this chapter shows you how to write the code to make this process work, starting with creating a new ASP.NET MVC project. Starting an ASP.NET MVC Project Just as with any other project in VS, you open the New Project window by selecting File | New | Project. Then create an ASP.NET MVC 2 Web Application project named MyShopCS (MyShopVB for VB). VS will ask if you want to create a test project, and Figure 9-1 The Model View Controller pattern ModelView Controller Request 252 Microsoft Visual Studio 2010: A Beginner’s Guide you have the option to choose Yes or No. Choosing Yes will add a unit testing project to the solution. You can choose either option, which won’t matter right now because we’ll not be covering this topic here, but it is definitely worth exploring on your own. Figure 9-2 shows the new project in Solution Explorer. VS created several folders with working code: ● The Model, View, and Controller folders hold code for the MVC Models, Views, and Controllers, respectively. ● Previous chapters already explained the purpose of the Properties and References folders. ● The App_Data folder is designed to allow you to ship a local database with your application and is ideal for small programs where you can use the free SQL Express database. See the accompanying note to learn how to add a database in the App_Data folder. ● The Content folder is where you add any Cascading Style Sheets (CSS) files. CSS is a standardized language for defining layout and appearance of a Web site. Figure 9-2 A new ASP.NET MVC project Chapter 9: Creating Web Applications with ASP.NET MVC 253 ● The Scripts folder holds JavaScript files, which include the jQuery and ASP.NET AJAX client libraries. JavaScript helps make Views more interactive and can be effective in providing a pleasing user experience. ● The Global.asax file holds code that runs at different periods during the application life cycle; we’ll investigate this file when looking at routing later in this chapter. ● The web.config file holds configuration information, such as database connection strings and more items that you don’t want to hard-code into the application. NOTE If you want to ship a local database with your application, you can right-click the App_ Data folder for your project, select Add | New Item, navigate to Data, and select SQL Server Database. This will add a blank database *.mdf file under the App_Data folder. You can work with this database through Server Explorer, using techniques learned in Chapter 7, to add tables and other objects. Remember that the server you deploy to must have SQL Server Express installed or your database operations won’t work. The code generated by the New Project Wizard will run, and pressing F5 to execute the application will show you a screen similar to Figure 9-3. Click OK when you see a screen that asks if you want to program to run in debug mode. This will modify the web.config file to allow debugging, which is what you want while developing applications. Figure 9-3 Running the default code produced by an ASP.NET MVC project 254 Microsoft Visual Studio 2010: A Beginner’s Guide The skeleton code produced by VS gives you some working examples that you can build on and move forward. One item that VS doesn’t produce is the Model, which is discussed next. Creating the Models As stated previously, the Model represents the data for the application. The example in this section uses LINQ to SQL to produce the Model for this application. To create the Model, add a LINQ to SQL entity Model by right-clicking the Models folder, selecting Add | New Item, and selecting LINQ to SQL. This creates a *.dbml file that you should add Customer and Order entities to, using the same techniques described in Chapter 7. In more sophisticated scenarios, you would have additional objects that held business logic or other data that isn’t associated with LINQ to SQL. This book keeps tasks at a basic level so that you can understand how to use VS. You can put Model objects in the Models folder or a separate class library. This chapter uses the Models folder. Building Controllers Requests come directly to a Controller, which we discussed earlier. As shown in Figure 9-2, the MVC project has a Controllers folder. Controller classes normally reside in the Controllers folder. Figure 9-2 shows two files, AccountController.cs and HomeController.cs, in the Controllers folder. Listing 9-1 shows the contents of the HomeController.cs file. Listing 9-1 The HomeController class C#: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyShopCS.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; Chapter 9: Creating Web Applications with ASP.NET MVC 255 return View(); } public ActionResult About() { return View(); } } } VB: <HandleError()> _ Public Class HomeController Inherits System.Web.Mvc.Controller Function Index() As ActionResult ViewData("Message") = "Welcome to ASP.NET MVC!" Return View() End Function Function About() As ActionResult Return View() End Function End Class Listing 9-1 demonstrates how closely ASP.NET MVC is tied to conventions. Notice that the class name is HomeController. Appending Controller to a class name is a convention that ASP.NET MVC uses to identify which classes are controllers. Also, the methods in the class are referred to as Actions in ASP.NET MVC. Using the Controllers folder for a Controller, appending the class name with Controller, and available actions are all conventions that you must follow. The following URL, a browser address, demonstrates how these conventions support routing to find a Controller and invoke the About action. You can see this URL if you run the application and click the About tab: http://localhost:1042/Home/About The http://localhost:1042 part of the URL is a Web server that is built into VS and runs the Web application without needing a Web server such as Internet Information Server (IIS). The number 1042 is a random port number generated by the Web server, and your port number is likely to be different. 256 Microsoft Visual Studio 2010: A Beginner’s Guide TIP You can change your VS Web server’s port number. If you open your project’s property page by right-mouse clicking on the project in Solution Explorer and select Properties, then select the Web tab on the left, under Servers, you can specify a specific port or make other Web server choices. For ASP.NET MVC, the important part of the URL is /Home/About. Home is the name of the Controller, and ASP.NET MVC appends Controller to the URL name, looking for the HomeController class, shown in Listing 9-1, physically located in the Controller folder, which is why it’s important to ensure you create files in the proper locations. About is an action, which corresponds to the About method shown in Listing 9-1. Similar to the About method, the Index action is run through the following URL: http://localhost:1042/Home/Index In a later section of this chapter, you’ll learn how ASP.NET MVC performs routing, which maps URLs to Controllers. Both the Index and About actions in Listing 9-1 invoke a method named View. This is a convention for invoking a View with the same name as the action method. For example, calling View in the Index action will show a View named Index, and the call to View in the About method will show a View named About. One more item to point out is how the Index action assigns a string to a collection called ViewData. The ViewData collection is one way for a Controller to pass Model data to a View. I’ll cover more on Controllers, including how to create your own, in a later part of this chapter, but now, let’s do a quick review of Views so that you can see what happens when they are invoked by the Controller. Displaying Views A View is what displays in the browser and allows interaction with the user. The View can display any information that a Controller passes to it. For example, notice that the Index action in Listing 9-1 assigns a string “Welcome to ASP.NET MVC!” with the “Message” key in the ViewData collection. Looking Inside a View Figure 9-3 shows the View in the browser, displaying the message. Listing 9-2 shows the Hypertext Markup Language (HTML) of the View displaying the message. The View actually has a combination of HTML and ASP.NET markup, sometimes referred to as ASPX, but I’ll refer to it as just HTML for the rest of the chapter. . 249 Chapter 9 Creating Web Applications with ASP.NET MVC 250 Microsoft Visual Studio 2010: A Beginner’s Guide Key Skills & Concepts ● Learn What MVC Means ● Create Models ●. Figure 9-1 The Model View Controller pattern ModelView Controller Request 252 Microsoft Visual Studio 2010: A Beginner’s Guide you have the option to choose Yes or No. Choosing Yes will add a. applications. Figure 9-3 Running the default code produced by an ASP.NET MVC project 254 Microsoft Visual Studio 2010: A Beginner’s Guide The skeleton code produced by VS gives you some working examples