ITPub博客

首页 > Linux操作系统 > Linux操作系统 > ASP.NET MVC Unleashed (2)

ASP.NET MVC Unleashed (2)

原创 Linux操作系统 作者:geez 时间:2009-03-01 21:49:06 0 删除 编辑
Chapter 2 - Building a Simple ASP.NET MVC Application 
In the previous chapter, we discussed all of the lofty goals of the ASP.NET MVC framework. In this chapter, we completely ignore them. In this chapter, we build a simple database-driven ASP.NET MVC application in the easiest way possible. We ignore design principles and patterns. We don’t create a single unit test. The goal is to clarify the basic mechanics of building an ASP.NET MVC application.
Over the course of this chapter, we build a simple Toy Store application. Our Toy Store application will enable us to display a list of toys and create new toys. In other words, it will illustrate how to build a web application that performs basic database operations. 
*** Begin Note ***
The third part of this book is devoted to an extended walkthrough of building an ASP.NET MVC application in the “right” way. We build a forums application by using test-driven development and software design principles and patterns.
*** End Note ***
第二章 – 创建一个简单的ASP.NET MVC应用程序
前一章里,我们讨论了ASP.NET MVC框架所有的理想目标。本章我们先完全忽略它们,我们将用最简单的方式创建一个简单的数据库驱动的ASP.NET MVC应用程序。我们忽略前面提到的设计原则和设计模式,我们也不写任何单元测试。将ASP.NET MVC应用程序的机制阐述清楚才是目的。
我们将在本章创建一个简单的“玩具店”应用程序,能够显示玩具的清单,创建新的玩具等。换句话说,它展示了如何创建一个能够执行基本数据库操作的Web应用。
本书的第三部分将深入探讨如何以“正确”的方式创建ASP.NET MVC应用程序,到时我们将使用测试驱动的开发过程以及软件设计原则和设计模式来创建一个论坛应用程序。

Starting with a Blank Slate
Let’s start by creating a new ASP.NET MVC application and removing all of the sample files. Follow these steps to create a new ASP.NET MVC Web Application Project:
1. Launch Visual Studio 2008.
2. Select the menu option File, New Project.
3. In the New Project dialog, select your preferred programming language and select the ASP.NET MVC Web Application template (see Figure 1).
4. Name your new project ToyStore and click the OK button.

Figure 1 – Creating a new ASP.NET MVC application

clip_image002


When you create a new ASP.NET MVC project, the Create Unit Test Project dialog appears automatically (see Figure 2). When asked whether you want to create a unit test project, select the option Yes, create a unit test project (In general, you should always select this option because it is a pain to add a new unit test project to your solution after your ASP.NET MVC project is already created).
*** Begin Note ***
The Create Unit Test Project dialog won’t appear when you create an ASP.NET MVC application in Microsoft Visual Web Developer. Visual Web Developer does not support Test projects.
*** End Note ***
As we discussed in the previous chapter, when you create a new ASP.NET MVC application you get several sample files by default. These files will get in our way as we build a new application. Delete the following files from your ASP.NET MVC project:
从空白开始
让我们来创建一个新的ASP.NET MVC应用程序并删除所有的示例文件。请按照下列步骤创建一个新的ASP.NET MVC Web应用程序项目;
1. 启动Visual Studio 2008.
2. 选择文件->新建项目菜单。
3. 在新建项目对话框里,选择您希望的编程语言并选择ASP.NET MVC Web应用程序模板(见图1)
4. 将项目命名为ToyStore并点击OK按钮。
图1 – 创建一个新的ASP.NET MVC应用程序
当您创建新的ASP.NET MVC项目时,“创建单元测试项目”对话框将自动出现(见图2),选择“是的,创建一个单元测试项目”选项(通常而言,您应当始终选择该选项,因为当ASP.NET MVC项目创建以后再向解决方案里添加新的单元测试项目是非常麻烦的)
图2 – 创建单元测试对话框

Figure 2 – The Create Unit Test Project dialog

clip_image004

当您用Microsoft Visual Web Developer创建ASP.NET MVC应用程序时,不会出现“创建单元测试项目”对话框,Visual Web Developer不支持测试项目。
正如我们在上章中所讨论的,当您创建一个新的ASP.NET MVC应用程序后,默认将为您创建几个示例文件,我们创建新的应用时,这些默认文件反而碍事,因此从您的ASP.NET MVC应用程序中删除下列文件:
[C#]
\Controllers\HomeController.cs
\Views\Home\About.aspx
\Views\Home\Index.aspx
从测试项目中删除以下文件.
[C#]
\Controllers\HomeControllerTest.cs

*** Begin Tip ***
If you always want to start with an empty ASP.NET MVC project then you can create a new Visual Studio project template after deleting the sample files. Create a new project template by selecting the menu option File, Export Template.
*** End Tip ***
【提示】如果您希望始终创建新的空白ASP.NET MVC项目,那么您可以在删除示例文件后,创建一个新的Visual Studio项目模板。选择“文件->导出模板”菜单可以创建一个新的项目模板。

Creating the Database
We need to create a database and database table to contain our list of toys for our toy store. The ASP.NET MVC framework is compatible with any modern database including Oracle 11g, MySQL, and Microsoft SQL Server.
In this book, we’ll use Microsoft SQL Server Express for our database. Microsoft SQL Server Express is the free version of Microsoft SQL Server. It includes all of the basic functionality of the full version of Microsoft SQL Server (it uses the same database engine). 
*** Begin Note ***
You can install Microsoft SQL Server Express when you install Visual Studio or Visual Web Developer (it is an installation option). You also can download Microsoft SQL Server Express by using the Web Platform. Installer which you can download from the following website:
http://www.asp.net/downloads/
*** End Note ***
Follow these steps to create a new database from within Visual Studio:
1. Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
2. In the Add New Item dialog, select the SQL Server Database template (see Figure 3).
3. Give the new database the name ToyStoreDB.
4. Click the Add button.
创建数据库
我们需要创建一个数据库和数据表,以容纳我们玩具店里的玩具清单。ASP.NET MVC框架兼容现代所有主流数据库系统,包括Oracle 11g,MySQL,及Microsoft SQL Server。
本书中,我们将使用Microsoft SQL Server Express作为我们的数据库,Microsoft SQL Server Express是Microsoft SQL Server的免费版本,它包含了Microsoft SQL Server完整版本的所有基本功能(它们使用相同的数据库引擎)。
【注意】您在安装Visual Studio或Visual Studio Web Developer时便可安装Microsoft SQL Server Express(它是一个安装选项)。您还可以从以下地址下载Web Platform. Installer并安装Microsoft SQL Server Express。
http://www.asp.net/downloads/
按照以下步骤在Visual Studio中创建一个新的数据库:
1. 鼠标右键点击解决方案浏览器窗口的App_Data文件夹,选择“添加->新项”。
2. 在“添加新项”对话框中,选择SQL Server Database模板(见图3)。
3. 将新数据库命名为ToyStoreDB。
4. 点击“添加”按钮。
图3 – 添加一个新的SQL Server数据库

Figure 3 – Adding a new SQL Server database

clip_image006

After you create the database, you need to create the database table that will contain the list of toys. Follow these steps to create the Products database table:
1. Double-click the ToyStoreDB.mdf file in the App_Data folder to open the Server Explorer window and connect to the ToyStoreDB database.
2. Right-click the Tables folder and select the menu option Add New Table.
3. Enter the columns listed in Table 1 into the Table Designer (see Figure 4).
4. Set the Id column as an Identity column by expanding the Identity Specification node under Column Properties and setting the (Is Identity) property to the value Yes.
5. Set the Id column as the primary key column by selecting this column in the Table Designer and clicking the Set Primary Key button (the button with an icon of a key).
6. Save the new table by clicking the Save button (the button with the anachronistic icon of a floppy disk).
7. In the Choose Name dialog, enter the table named Products. 
数据库创建完成后,您需要在其中创建一个包含玩具清单的数据表。
1.双击App_Data目录下的ToyStoreDB.mdf文件,打开服务器浏览器窗口并连接到ToyStoreDB数据库。
2.鼠标右键点击Tables文件夹并选择Add New Table菜单项。
3.在表设计器里依次输入表1列出的列(见图4)。
4.将Id列设置为标识(Identity)列,方法是展开“列属性”的标识规范节点并将“Is Identity”属性设置为Yes。
5.将Id列设置为主键列,方法是在表设计器中选中该列并点击“设置为主键”按钮(标有钥匙图标的按钮)。
6.点击“保存”按钮保存新建的表(标有磁盘图标的按钮)。
7.在“Choose Name”对话框中,将表名输入为Products。

Table 1 – Columns in the Products table

Column NameData TypeAllow Nulls
Idintfalse
Namenvarchar(100)false
Descriptionnvarchar(MAX)false
Pricemoneyfalse

Figure 4 – Creating the Products table

clip_image008 
*** Begin Note ***
The Server Explorer window is called the Database Explorer window in the case of Visual Web Developer.
*** End Note ***
After you finish creating the Products database table, you should add some database records to the table. Right-click the Products table in the Server Explorer window and select the menu option Show Table Data. Enter two or three products (see Figure 5).

Figure 5 – Entering sample data in the Products database table

clip_image010

Creating the Model
We need to create model classes to represent our database tables in our ASP.NET MVC application. The easiest way to create the data model classes is to use an Object Relational Mapping (ORM) tool to generate the classes from a database automatically.
You can use your favorite ORM with the ASP.NET MVC framework. The ASP.NET MVC framework is not tied to any particular ORM. For example, ASP.NET MVC is compatible with Microsoft LINQ to SQL, NHibernate, and the Microsoft Entity Framework. 
In this book, we use the Microsoft Entity Framework to generate our data model classes. We focus on the Microsoft Entity Framework because the Microsoft Entity Framework is Microsoft’s recommended data access solution. 
*** Begin Note ***
In order to use the Microsoft Entity Framework, you need to install .NET Framework 3.5 Service Pack 1.
*** End Note ***
Follow these steps to generate the data model classes:
1. Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
2. Select the Data category and the ADO.NET Entity Data Model template (see Figure 6).
3. Name the data model ToyStoreDataModel.edmx and click the Add button.
【注意】服务器浏览器窗口在Visual Web Developer里称为数据库浏览器窗口。
在完成Products数据表的创建后,您应当往表中添加几条记录。鼠标右击服务器浏览器窗口并选择“显示表中数据”菜单项,在其中输入2、3条记录(见图5)。
创建模型
我们需要为我们的ASP.NET MVC应用程序创建模型类,来表示数据库中的数据表。最简单的方法是使用对象-关系映射(ORM)工具从数据库自动生成数据类,来创建数据模型类。
您可以在ASP.NET MVC框架里使用您最喜爱的ORM工具,ASP.NET MVC框架没有与任何特定的ORM绑定。例如,ASP.NET MVC与Microsoft LINQ to SQL,NHibernate,以及Microsoft 实体框架(Microsoft Entity Framework)均兼容。
本书中,我们使用Microsoft 实体框架来生成我们的数据模型类,之所以采用Microsoft 实体框架是应为它是Microsoft 推荐的数据访问解决方案。
【注意】您需要安装.NET Framework 3.5 SP1才能使用Microsoft 实体框架。
按以下步骤生成数据访问类:
1. 鼠标右击解决方案浏览器窗口的Models文件夹,选择Add->New Item菜单项。
2. 选择Data类别,再选择ADO.NET Entity Data Model模板(见图6)。
3. 将数据模型命名为ToyStoreDataModel.edmx并点击Add按钮。

Figure 6 – Adding ADO.NET Entity Data Model classes

clip_image012

After you complete these steps, the Entity Model Data Wizard launches. Complete these wizard steps:
1. In the Choose Model Contents step, select the Generate from database option.
2. In the Choose Your Data Connection step, select the ToyStoreDB.mdf data connection and the entity connection name ToyStoreDBEntities (see Figure 7).
3. In the Choose Your Database Objects step, select the Products database table and enter Models for the namespace (see Figure 8).
4. Click the Finish button to complete the wizard.

在您完成以上步骤后,实体模型数据向导窗口会弹出。按以下步骤完成向导:
1. 在“选择模型内容”这一步骤,选择“从数据库生成”选项。
2. 在“选择数据连接”步骤里,选择ToyStoreDB.mdf数据连接并将实体连接命名为ToyStoreDBEntities(见图7)。
3.在“选择数据库对象”这一步里,选择Products数据表,在名称空间处填写Models(见图8)。
4. 点击完成按钮结束向导。

Figure 7 – Choose your data connection

clip_image014

Figure 8 – Entering the model namespace

clip_image016

After you complete the Entity Data Model Wizard, the Entity Designer appears with a single entity named Products (see Figure 9). The Entity Framework has generated a class named Products that represents your Products database table. 
Most likely, you’ll want to rename the classes generated by the Entity Framework. The Entity Framework simply names its entities with the same names as the database tables. Because the Products class represents a particular product, you’ll want to change the name of the class to Product (singular instead of plural). 
Right-click the Products entity in the Entity Designer and select the menu option Rename. Provide the new name Product.
At this point, we have successfully created our data model classes. We can use these classes to represent our ToyStoreDB database within our ASP.NET MVC application.
*** Begin Note ***
You can open the Entity Designer at any time in the future by double-clicking the ToyStoreDataModel.edmx file in the Models folder.
*** End Note ***
在完成“实体数据模型向导”后,将显示“实体设计器”,其中仅有一个名为Products的实体类(见图9),实体框架已为您生成了一个Products类,表示您数据库中的Products数据表。
您很有可能会希望能对实体框架生成的类重新命名,实体框架仅仅简单地用数据库的表名来命名实体。由于Products类表示一个特定的产品,因此您会希望修改其名称为Product(用单数替代复数)。

Figure 9 – The Entity Designer

clip_image018

到此,我们已经成功地创建了我们的数据模型类。我们能够使用这些类来表示ASP.NET MVC应用程序中的ToyStoreDB数据库。

Creating the Controller
The controllers in an ASP.NET MVC application control the flow of application execution. The controller that is invoked by default is named the Home controller. We need to create the Home controller by following these steps:
1. Right-click the Controllers folder and select the menu option Add Controller.
2. In the Add Controller dialog, enter the controller name HomeController and select the option labeled Add action methods for Create, Update, and Details scenarios (see Figure 10). 
3. Click the Add button to create the new controller.
创建控制器
ASP.NET MVC应用程序中的控制器用来控制应用的执行流,默认情况下会调用Home控制器。我们需要按以下步骤来创建一个Home控制器:
1. 鼠标右击Controllers文件夹并选择“Add Controller”菜单项。
2. 在“Add Controller”对话框中,输入HomeController控制器名称并勾上“Add action methods for Create, Update, and Details scenarios”选项(见图10)。
3. 点击Add按钮从而添加这个新的控制器。
列表1给出了创建的Home控制器类:

Figure 10 – Adding a new controller

clip_image020

The Home controller is contained in Listing 1.
Listing 1 – Controllers\HomeController.cs [C#]
1. using System;   
2. using System.Collections.Generic;   
3. using System.Linq;   
4. using System.Web;   
5. using System.Web.Mvc;   
6. using System.Web.Mvc.Ajax;   
7.  
8. namespace ToyStore.Controllers   
9. {   
10.    public class HomeController : Controller   
11.    {   
12.        //   
13.        // GET: /Home/   
14.  
15.        public ActionResult Index()   
16.        {   
17.            return View();   
18.        }   
19.  
20.        //   
21.        // GET: /Home/Details/5   
22.  
23.        public ActionResult Details(int id)   
24.        {   
25.            return View();   
26.        }   
27.  
28.        //   
29.        // GET: /Home/Create   
30.  
31.        public ActionResult Create()   
32.        {   
33.            return View();   
34.        }    
35.  
36.        //   
37.        // POST: /Home/Create   
38.  
39.        [AcceptVerbs(HttpVerbs.Post)]   
40.        public ActionResult Create(FormCollection collection)   
41.        {   
42.            try  
43.            {   
44.                // TODO: Add insert logic here   
45.  
46.                return RedirectToAction("Index");   
47.            }   
48.            catch  
49.            {   
50.                return View();   
51.            }   
52.        }   
53.  
54.        //   
55.        // GET: /Home/Edit/5   
56.    
57.        public ActionResult Edit(int id)   
58.        {   
59.            return View();   
60.        }   
61.  
62.        //   
63.        // POST: /Home/Edit/5   
64.  
65.        [AcceptVerbs(HttpVerbs.Post)]   
66.        public ActionResult Edit(int id, FormCollection collection)   
67.        {   
68.            try  
69.            {   
70.                // TODO: Add update logic here   
71.    
72.                return RedirectToAction("Index");   
73.            }   
74.            catch  
75.            {   
76.                return View();   
77.            }   
78.        }   
79.    }   
80. }  

Because we selected the option to generate Create, Update, and Details methods when creating the Home controller, the Home controller in Listing 1 includes these actions. In particular, the Home controller exposes the following actions:
• Index() – This is the default action of the controller. Typically, this action is used to display a list of items.
• Details(id) – This action displays details for a particular item.
• Create() -- This action displays a form. for creating a new item.
• Create(collection) – This action inserts the new item into the database.
• Edit(id) – This action displays a form. for editing an existing item.
• Edit(id, collection) -- This action update the existing item in the database.
由于我们在创建Home控制器时,选中了生成Create, Update, 以及Details方法,列表1的Home控制器类中包括了这些行为,特别地,Home控制器里还包括了以下行为:
• Index() – 这是控制器的默认行为。典型地,这个行为用来显示一个记录的清单。
• Details(id) –该行为用来显示某个记录的详细信息。
• Create() – 该行为用来创建一个新的记录。
• Create(collection) –该行为用来往数据库里插入一个记录。
• Edit(id) – 该行为显示一个编辑现有记录的表单。
• Edit(id, collection) – 该行为更新数据库中的现有记录。
Currently, the Home controller only contains stubs for these actions. Let’s go ahead and take advantage of the data model classes that we created with the Entity Framework to implement the Index() and Create() actions. The updated Home controller is contained in Listing 2.
目前,Home控制器中仅包含这些行为的代码片段(stub)。我们继续利用实体框架创建的数据模型类来实现Index()和Create()行为。列表2显示了修改后的Home控制器。
Listing 2 – Controllers\HomeController.cs [C#]
1. using System.Linq;   
2. using System.Web.Mvc;   
3. using ToyStore.Models;   
4.  
5. namespace ToyStore.Controllers   
6. {   
7.    public class HomeController : Controller   
8.    {   
9.        private ToyStoreDBEntities _dataModel = new ToyStoreDBEntities();    
10.                  
11.        //   
12.        // GET: /Home/   
13.  
14.        public ActionResult Index()   
15.        {   
16.            return View(_dataModel.ProductSet.ToList());   
17.        }   
18.  
19.        //   
20.        // GET: /Home/Create   
21.  
22.        public ActionResult Create()   
23.        {   
24.            return View();   
25.        }    
26.  
27.        //   
28.        // POST: /Home/Create   
29.  
30.        [AcceptVerbs(HttpVerbs.Post)]   
31.        public ActionResult Create(Product productToCreate)   
32.        {   
33.            try  
34.            {   
35.                _dataModel.AddToProductSet(productToCreate);   
36.                _dataModel.SaveChanges();   
37.  
38.                return RedirectToAction("Index");   
39.            }   
40.            catch  
41.            {   
42.                return View();   
43.            }   
44.        }   
45.  
46.  
47.    }   
48. }  

Notice that a private field named _dataModel of type DBStoreEntities is defined at the top of the controller in Listing 2. The DBStoreEntities class was one of the classes that were generated by the Entity Model Data Wizard. We use this class to communicate with the database.
The Index() action has been modified to return a list of products. The expression _dataModel.ProductSet.ToList() returns a list of products from the Products database table.
There are two Create() actions. The first Create() action displays the form. for creating a new product. The form. is submitted to the second Create() action which actually performs the database insert of the new product.
Notice that the second Create() action has been modified to accept a Product parameter. The Product class also was generated by the Entity Model Data Wizard. The Product class has properties that correspond to each column in the underlying Products database table.
Finally, the Create() action calls the following methods to add the new product to the database:
[C#]
_dataModel.AddToProductSet(productToCreate);
_dataModel.SaveChanges();
Our Home controller now contains all of the necessary database logic. We can use the controller to return a set of products and we can use the controller to create a new product.
Notice that both the Index() action and the first Create() action return a View. The next and final step is to create these views.
请留意列表2中控制器定义上方定义的类型为DBStoreEntities的私有域_dataModel。DBStoreEntities是实体模型数据向导的生成类之一,我们用它来与数据库通讯。
Index()行为被修改为返回一个产品清单。表达式_dataModel.ProductSet.ToList()返回Products数据库表里数据的一个列表。
有两个Create()行为,第一个Create()行为显示一个创建新的产品的表单,提交这个表单将会转到第二个Create()行为,该行为真正执行往数据库中插入一条新的产品记录。
注意第二个Create()行为被修改为接受一个Product参数,Product类也是又实体模型数据向导自动生成的,对于底层Products数据表的每一个列,该类中都有对应的属性。
[C#]
_dataModel.AddToProductSet(productToCreate);
_dataModel.SaveChanges();
我们的Home控制器现在包含了所有必须的数据库访问逻辑,我们能够使用控制器返回产品清单,也能够使用控制器创建一个新的产品。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/740297/viewspace-558224/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-02-03

  • 博文量
    21
  • 访问量
    65380