您的位置:首页 > 编程语言 > ASP

[翻译]15分钟内创建一个电影的ASP.NET MVC数据库应用程序

2009-10-21 02:11 746 查看
The purpose of this tutorial is to give you a sense of "what it is like" to build an ASP.NET MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application from start to finish. I show you how to build a simple database-driven application that illustrates how you can list, create, and edit database records.

这节的目的是让你对ASP.NET MVC有一个感性上的认识,在这里将和我一起从头到尾创建一个ASP.NET MVC应用,我将使用图文并茂的方式向你展示创建一个简单的数据驱动的应用中的列表、新增和修改数据库的记录。

To simplify the process of building our application, we’ll take advantage of the scaffolding features of Visual Studio 2008. We’ll let Visual Studio generate the initial code and content for our controllers, models, and views.

在创建这个简单的应用程序过程中我们利用Visual Studio 2008的特性,我们使用Visual Studio自动创建代码和内容的功能来创建我们的【控制器】、【模型】、【视图】。

If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC provides you with full access to the rich set of languages and classes provided by the .NET framework.

如果你使用过ASP或ASP.NET写过程序那么你将非常容易上手ASP.NET MVC,ASP.NET MVC的【视图】非常像ASP程序的页面并且也很像传统的ASP.NET Web Forms应用,ASP.NET MVC让你完全使用.Net framework并提供了丰富语言的类。

My hope is that this tutorial will give you a sense of how the experience of building an ASP.NET MVC application is both similar and different than the experience of building an Active Server Pages or ASP.NET Web Forms application.

我希望这节可以让你感受到创建ASP.NET MVC应用程序与ASP或 ASP.NET Web Forms应用程序的相同点和不同点的感觉。

Overview of the Movie Database Application
电影数据库程序概述
Because our goal is to keep things simple, we’ll build a very simple Movie Database application. Our simple Movie Database application will allow us to do three things:

因为我们的目标是保持事情的简单,所以我们创建一个简单的电影数据库应用程序,并且只让应用程序只做三件事情:

1. List a set of movie database records

2. Create a new movie database record

3. Edit an existing movie database record

1. 显示电影数据的记录列表。

2. 创建一条新的电影记录。

3. 修改一条已存在的记录。

Again, because we want to keep things simple, we’ll take advantage of the minimum number of features of the ASP.NET MVC framework needed to build our application. For example, we won’t be taking advantage of Test-Driven Development.

接着,为了保证事情简单,我们只利用ASP.NET MVC框架所需的最小特性来创建我们的应用程序,比如我们不使用【测试驱动开发】。

In order to create our application, we need to complete each of the following steps:

为了创建我们的应用程序,我们需要完成下面的事情:

Create the ASP.NET MVC Web Application Project

Create the database

Create the database model

Create the ASP.NET MVC controller

Create the ASP.NET MVC views

创建ASP.NET MVC Web Application工程

创建数据库

创建数据模型

创建控制器

创建视图

Preliminaries
准备环境
You’ll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework.

If you don’t own Visual Studio 2008, then you can download a 90 day trial version of Visual Studio 2008 from this website:

你需要任何一个版本的Visual Studio 2008或是速成版的Visual Web Developer 2008来创建ASP.NET MVC应用程序,同样你需要下载ASP.NET MVC框架。

如果没有Visual Studio 2008可以从下面的网站中下载一个90天试用版的Visual Studio 2008。

http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx

Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from this website:

注意,你可以在速成版的Visual Web Developer 2008中创建ASP.NET MVC应用程序,如果你决定使用速成版的Visual Web Developer 2008必须要安装SP1的补丁,你可以通过下面的网站下载SP1的补丁。

http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154-6DF4F6DEBD14&displaylang=en

After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the following website:

如果你已经安装了Visual Studio2008或是速成版的Visual Web Developer 2008,那你只需要安装ASP.NET MVC框架就可以了,你可以从下面的网站上下载ASP.NET MVC框架。

http://www.asp.net/mvc/

Creating an ASP.NET MVC Web Application Project
创建一个ASP.NET MVC Web Application工程
Let’s start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. Select C# as the programming language and select the ASP.NET MVC Web Application project template. Give your project the name MovieApp and click the OK button.

现在开始在Visual Studio 2008中创建一个新的ASP.NET MVC Web Application工程,选择文件菜单,新建工程,可以看到出现了新建工程对话框。1.选择C#应用程序并且选择ASP.NET MVC Web Application工程模板,给你的工程起一个MovieApp的名字,然后点击OK按钮。





Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. The dialog in Figure 2 appears. Because we won’t be creating tests in this tutorial because of time constraints (and, yes, we should feel a little guilty about this) select the No option and click the OK button.

无论你在任何时候创建一个新的ASP.NET MVC Web Application工程Visual Studio都会提示你是否创建一个【单元测试】工程,这个对话框如下图,因为我们在本节中因为时间限制所以不再创建测试(也许我们有一点罪恶感)选择【不,我不创建单元测试工程】然后点击OK。





An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window. We’ll need to add files to each of the Models, Views, and Controllers folders in order to build our Movie Database application.

一个ASP.NET MVC应用程序标准的文件夹:一个Models,一个Views和Controllers文件夹,你可以在解决方案中看到这些文件夹,我们需要为我们的电影数据库应用程序中的文件夹中增加文件。

When you create a new MVC application with Visual Studio, you get a sample application. Because we want to start from scratch, we need to delete the content for this sample application. You need to delete the following file and the following folder:

使用Visual Studio创建的新的MVC后将会得到了一个简单的应用程序,因为我们需要从头开始,所以我们需要删除掉内容,你需要删除掉下面的文件和文件夹。

l Controllers/HomeController.cs

l Views/Home

Creating the Database
创建数据库
We need to create a database to hold our movie database records. Luckily, Visual Studio includes a free database named SQL Server Express. Follow these steps to create the database:

我们需要创建数据库来存放电影数据记录,幸运的是Visual Studio已经内置了免费的SQL Server Express。接下来我们按以下步骤来创建数据库。

Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.

在解决方案窗口中右键点击App_Data文件夹,点击新增,增加新项。

Select the Data category and select the SQL Server Database template (see Figure 3).

Name your new database MoviesDB.mdf and click the Add button.

After you create your database, you can connect to the database by double-clicking the MoviesDB.mdf file located in the App_Data folder. Double-clicking the MoviesDB.mdf file opens the Server Explorer window.

选择数据分类然后选择SQL Server 数据库模板,如下图。

将数据库命名为MoviesDB.mdf,点击增加按钮。

创建好你的数据库之后你要双击连接数据库。





Next, we need to create a new database table. From within the Sever Explorer window, right-click the Tables folder and select the menu option Add New Table. Selecting this menu option opens the database table designer. Create the following database columns:

接下来,我们需要从服务器窗口中创建一个数据表,右键【表】文件夹然后选择增加菜单,增加表,选择数据表打开数据表设计器,创建如下的列:
Column Name

Data Type

Allow Nulls

Id

Int

False

Title

Nvarchar(100)

False

Director

Nvarchar(100)

False

DateReleased

DateTime

False

The first column, the Id column, has two special properties. First, you need to mark the Id column as the primary key column. After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id column as an Identity column. In the Column Properties window, scroll down to the Identity Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.

第一列是ID列,它有两个特殊的属性,第一,你需要将这一列设为主键列,选择ID列之后点击设为主键(它是一个看起来象钥匙的图标)。第二,你需要将ID列设置为自增的列,在列的属性窗口中,下拉滚动条打到自动标识节并打开它,将【自增】属性设置为【是】完成设置,如下图:





The final step is to save the new table. Click the Save button (the icon of the floppy) and give the new table the name Movies.

最后一步保存表,点击保存按钮(象软盘的那个按钮)然的给表起一个名字。

After you finish creating the table, add some movie records to the table. Right-click the Movies table in the Server Explorer window and select the menu option Show Table Data. Enter a list of your favorite movies (see Figure 5).

创建表完成之后增加一点电影记录到表中,在服务器窗口中右键Movies表选择显示表格数据,输入一些您喜欢的电影的信息:





Creating the Model
创建模型
We next need to create a set of classes to represent our database. We need to create a database model. We’ll take advantage of the Microsoft Entity Framework to generate the classes for our database model automatically.

我们接下来需要创建一套描述我们数据库模型的映射类,我们利用Microsoft Entity Framework来自动创建数据库模型类。

The ASP.NET MVC framework is not tied to the Microsoft Entity Framework. You can create your database model classes by taking advantage of a variety of Object Relational Mapping (OR/M) tools including LINQ to SQL, Subsonic, and NHibernate.

注意:ASP.NET框架不依赖于Microsoft Entity Framework,你可以使用LINQ TO SQL将你的数据库映射类为【对象关系图ORM】,Subsonic或NHibernate。

Follow these steps to launch the Entity Data Model Wizard:

按照下面的步骤来创建Entity数据模型:

Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.

Select the Data category and select the ADO.NET Entity Data Model template.

Give your data model the name MoviesDBModel.edmx and click the Add button.

在解决方案窗口中右键Models文件夹,选择增加,增加新项。

选择【数据】分类,选择ADO.NET Entity Data Model模板。

给你的数据模型起一个名MoviesDBModel.edmx然后点击【增加】按钮。

After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). Follow these steps to complete the wizard:

点击增加按钮之后出现Entity Data Model向导,按照下来步骤完成向导:

In the Choose Model Contents step, select the Generate from database option.

In the Choose Your Data Connection step, use the MoviesDB.mdf data connection and the name MoviesDBEntities for the connection settings. Click the Next button.

In the Choose Your Database Objects step, expand the Tables node, select the Movies table. Enter the namespace MovieApp.Models and click the Finish button.

选择【从数据库生成】。

使用MoviesDB.mdf数据库连接

打开表节点,选择Movies表,输入命名空间MovieApp.Models点击完成按钮。





After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. The Designer should display the Movies database table (see Figure 7).

完成Entity Data Model向导之后,会打开Entity Data Model设计器,这个设计器显示Movies数据表,如图:





We need to make one change before we continue. The Entity Data Wizard generates a model class named Movies that represents the Movies database table. Because we’ll use the Movies class to represent a particular movie, we need to modify the name of the class to be Movie instead of Movies (singular rather than plural).

在继续之前我们需要更改一下名字,Entity Data向导生成的Model类名称为Movies与数据库表名一致,我们需要将Movies改为Movie,因为单数和复数的原因,每个实体实际上是一条记录。

Double-click the name of the class on the designer surface and change the name of the class from Movies to Movie. After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.

在设计器上双击类的名称把Movies更改为Movie,更改完成后点击保存。

Creating the ASP.NET MVC Controller
创建ASP.NET MVC控制器
The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.

下一步我们创建ASP.NET MVC的controller,控制器控制用户如何与ASP.NET MVC程序交互。

Follow these steps:

按照下列步骤:

In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.

In the Add Controller dialog, enter the name HomeController and check the checkbox labeled Add action methods for Create, Update, and Details scenarios (see Figure 8).

Click the Add button to add the new controller to your project.

在解决方案资源管理器中右键Controllers文件夹,选择增加,Controller。

在增加Controller对话框中输入HomeController名称,选中Add action methods for Create, Update, and Details scenarios复选框。如下图:

点击增加按钮完成。

After you complete these steps, the controller in Listing 1 is created. Notice that it contains methods named Index, Details, Create, and Edit. In the following sections, we’ll add the necessary code to get these methods to work.

完成了上面的步骤以后,在controller的清单中注释方法的内容索引Details,Create和Edit, 我们增加所需要的代码在这些方法中。





Listing Database Records
数据库记录列表
The Index() method of the Home controller is the default method for an ASP.NET MVC application. When you run an ASP.NET MVC application, the Index() method is the first controller method that is called.

Index()方法是HomeController的默认方法,当我们运行这个应用程序时将是它第一个执行。

We’ll use the Index() method to display the list of records from the Movies database table. We’ll take advantage of the database model classes that we created earlier to retrieve the movie database records with the Index() method.

我们利用数据库模型在Index()方法中显示Movies数据表中原始的记录。

I’ve modified the HomeController class in Listing 2 so that it contains a new private field named _db. The MoviesDBEntities class represents our database model and we’ll use this class to communicate with our database.

I’ve also modified the Index() method in Listing 2. The Index() method uses the MoviesDBEntities class to retrieve all of the movie records from the Movies database table. The expression _db.MovieSet.ToList() returns a list of all of the movie records from the Movies database table.

The list of movies is passed to the view. Anything that gets passed to the View() method gets passed to the view as view data.

我们修改HomeController类如下面的代码所示,增加一个private的MoviesDBEntities类型的字段_db,它是负责与我们的数据库进行通信。

我们同样修改Index()方法,如代码所示, MoviesDBEntitys类找到数据库里的全部记录。_db.MovieSet.ToList()表示返回Movie数据表中的全部记录。

View()方法将moives的列表传递到视图中的view data中去。

Listing 2 – Controllers/HomeController.cs (modified Index method)

using System.Linq;

using System.Web.Mvc;

using MovieApp.Models;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

private MoviesDBEntities _db = new MoviesDBEntities();

public ActionResult Index()

{

return View(_db.MovieSet.ToList());

}

}

}

The Index() method returns a view named Index. We need to create this view to display the list of movie database records. Follow these steps:

Index()方法返回一个名叫Index的视图,我们需要创建这个视图来显示movie数据库里的记录,按照下列步骤来做:

Right-click the Index() method in the code editor and select the menu option Add View

In the Add View dialog, verify that the checkbox labeled Create a strongly-typed view is checked.

From the View content dropdown list, select the value List.

From the View data class dropdown list, select the value MovieApp.Models.Movie.

Click the Add button to create the new view

在代码编辑视图下右键Index()方法,选择菜单中的Add View。图1

在增加视图的窗口中勾选上Create a strongly-typed view.

从下拉列表中选择List项。

从View data class下拉列表中选择MovieApp.Models.Movie图2

点击增加按钮创建一个新的视图。

After you complete these steps, a new view named Index.aspx is added to the Views/Home folder. The contents of the Index view are included in Listing 3.

创建视图完成之后新的视图命名为Index.aspx,它位于View/Home文件夹中,内容是显示列表。









Creating New Database Records
创建新的记录
The Index view that we created in the previous section includes a link for creating new database records. Let’s go ahead and implement the logic and create the view necessary for creating new movie database records.

在Index视图中有一个Create New的连接,可以增加一条新记录,我们需要实现一些逻辑来增加视图创建新电影记录。

The Home controller contains two methods named Create(). The first Create() method has no parameters. This overload of the Create() method is used to display the HTML form for creating a new movie database record.

在Home Contoller中包含有两个Create()方法,第一个Create()方法是不带参数的,这个重载的Create()方法是显示创建一条新记录的HTML。

The second Create() method has a FormCollection parameter. This overload of the Create() method is called when the HTML form for creating a new movie is posted to the server. Notice that this second Create() method has an AcceptVerbs attribute that prevents the method from being called unless an HTTP POST operation is performed.

第二个Create()方法有一个FormCollection参数,重载的Create()方法接收HTML表单提交上来的新的Moive数据到服务器上,注意:第二个Create()方法拥有一个AcceptVerbs属性标记防止非HTTP POST操作调用它。

This second Create() method has been modified in the updated HomeController class in Listing 4. The new version of the Create() method accepts a Movie parameter and contains the logic for inserting a new movie into the Movies database table.

第二个Create()方法改进了HomeContoller类,如下面的代码,新版本的Create()方法接收一个Movie参数并包含了一些插入新Moive的逻辑。

Notice the Bind attribute. Because we don’t want to update the Movie Id property from HTML form, we need to explicitly exclude this property.

注意:Bind属性,因为我们不想从HTML表单更新Moive的ID属性,我们需要明确的拒绝这个属性。

Listing 4 – Controllers/HomeController.cs (modified Create method)

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create([Bind(Exclude="Id")] Movie movieToCreate)

{

if (!ModelState.IsValid)

return View();

_db.AddToMovieSet(movieToCreate);

_db.SaveChanges();

return RedirectToAction("Index");

}

Visual Studio makes it easy to create the form for creating a new movie database record (see Figure 12). Follow these steps:

Right-click the Create() method in the code editor and select the menu option Add View.

Verify that the checkbox labeled Create a strongly-typed view is checked.

From the View content dropdown list, select the value Create.

From the View data class dropdown list, select the value MovieApp.Models.Movie.

Click the Add button to create the new view.

Visual Studio可以非常简单的创建一个新电影数据记录的View。按下列步骤操作如下图:

在代码编辑模式下在Create()方法上右键选择菜单中的Add New,勾选Create a strongly-typed view,在View data class下拉列表中选择MoiveApp.Models.Movie。View contect中选择Create。点击保存按钮完成。





Visual Studio generates the view in automatically. This view contains an HTML form that includes fields that correspond to each of the properties of the Movie class.

The HTML form generated by the Add View dialog generates an Id form field. Because the Id column is an Identity column, we don’t need this form field and you can safely remove it.

Visual Studio 自动生成View文件HTML内容,内容中包含了每一个Movie类的属性。

注意:HTML是从自动生成View对话框中生成的,里面有一个ID字段,因为ID列是标识列,我们不需要它,于是我们删掉。

After you add the Create view, you can add new Movie records to the database. Run your application by pressing the F5 key and click the Create New link to see the form in Figure 13. If you complete and submit the form, a new movie database record is created.

Notice that you get form validation automatically. If you neglect to enter a release date for a movie, or you enter an invalid release date, then the form is redisplayed and the release date field is highlighted.

在增加了Create视图之后我们增加一条新的Moive记录到数据库中,按F5动行我们的应用程序,点击Create New连接,如下图,如果我们完成了提交,那么就会在数据库中增加一条新的记录。

提示:你的表单会自动验证,如果你忽略输入电影的日期,或是输入了无效的日期,它个表单会高明这个无效日期。





Editing Existing Database Records
编辑已经存在的数据记录
In the previous sections, we discussed how you can list and create new database records. In this final section, we discuss how you can edit existing database records.

First, we need to generate the Edit form. This step is easy since Visual Studio will generate the Edit form for us automatically. Open the HomeController.cs class in the Visual Studio code editor and follow these steps:

在早前一节中我们讲述了如何显示一个列表并且增加一条新的记录到数据库中,在这一节中,我们将讲述如果编辑修改现有的数据库记录。

首先我们先创建一个Edit表单,使用Visual Studio自动生成Edit表单功能可以非常简单的实现,打开HomeController.cs类在代码编辑模式下进行下列的步骤:

Right-click the Edit() method in the code editor and select the menu option Add View (see Figure 14).

Check the checkbox labeled Create a strongly-typed view.

From the View content dropdown list, select the value Edit.

From the View data class dropdown list, select the value MovieApp.Models.Movie.

Click the Add button to create the new view.

在代码编辑模式下在Edit()方法中右键点击出现菜单中选择Add View如图

勾选Create a strongly-typed view复选框。

在View content下拉列表中选择Edit。

在View data class下拉列表中选择MovieApp.Models.Movie。

点击ADD按钮增加新的View。

Completing these steps adds a new view named Edit.aspx to the Views/Home folder. This view contains an HTML form for editing a movie record.

经常以上步骤我们就在Views/Home的文件夹中增加了一个名为Edit.aspx的视图,这个视图的内容是编辑一条电影记录的HTML。





The Edit view contains an HTML form field that corresponds to the Movie Id property. Because you don’t want people editing the value of the Id property, you should remove this form field.

注意:编辑视图包含一个电影ID属性相应的HTML表单字段,因为我们不打算人为更改它的值,所以我们删掉这个HTML表单字段。

Finally, we need to modify the Home controller so that it supports editing a database record. The updated HomeController class is contained.

最后我们需要修改Home controller来支持修改后更新数据库的目的,下面的代码

//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

var movieToEdit = (from m in _db.MovieSet

where m.Id == id

select m).First();

return View(movieToEdit);

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(Movie movieToEdit)

{

var originalMovie = (from m in _db.MovieSet

where m.Id == movieToEdit.Id

select m).First();

if (!ModelState.IsValid)

return View(originalMovie);

_db.ApplyPropertyChanges(originalMovie.EntityKey.EntitySetName, movieToEdit);

_db.SaveChanges();

return RedirectToAction("Index");

}

In above code, I’ve added additional logic to both overloads of the Edit() method. The first Edit() method returns the movie database record that corresponds to the Id parameter passed to the method. The second overload performs the updates to a movie record in the database.

Notice that you must retrieve the original movie, and then call ApplyPropertyChanges(), to update the existing movie in the database.

在上面的代码中,我们给予了重载的Edit()方法的逻辑,第一个Edit()方法根据id参数返回电影记录,第二个重载的方法接受一个Movie的参数来更新数据库。

注意:我们必须重新找到原始的Movie记录,然后调用ApplyPropertyChanges()更新数据库中已经存在的Movie记录。

Summary
概述
The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web application is very similar to the experience of building an Active Server Pages or ASP.NET application.

In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers

这个指南的目的是为了让你体验创建ASP.NET MVC应用程序的感觉,我希望你发觉创建ASP.NET MVC web应用程序很像创建 ASP或 ASP.NET应用程序的感觉。

在这个指南里我们只使用到了非常基础的ASP.NET MVC的特性,在接下来的指南里,我们将深度的研究controller、controller actions、views、view data、和HTML helpers。

----------------------------------完--------------------------------------------------

2009-10-21

鹏鹏(Peng)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐