mvc移动创建oracle表,使用 ASP.NET MVC (C#)在15分钟内创建电影数据库应用程序 | Microsoft Docs...

使用 ASP.NET MVC 在 15 分钟内创建电影数据库应用程序 (C#)Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#)

01/27/2009

本文内容

Stephen Walther 从头开始构建整个数据库驱动的 ASP.NET MVC 应用程序。Stephen Walther builds an entire database-driven ASP.NET MVC application from start to finish. 本教程非常介绍了 ASP.NET MVC 框架的新手,并希望了解构建 ASP.NET MVC 应用程序的过程。This tutorial is a great introduction for people who are new to the ASP.NET MVC Framework and who want to get a sense of the process of building an ASP.NET MVC application.

本教程的目的是让你了解一下如何构建 ASP.NET MVC 应用程序。The purpose of this tutorial is to give you a sense of "what it is like" to build an ASP.NET MVC application. 在本教程中,我将从开始到完成构建整个 ASP.NET MVC 应用程序。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.

为了简化生成应用程序的过程,我们将利用 Visual Studio 2008 的基架功能。To simplify the process of building our application, we'll take advantage of the scaffolding features of Visual Studio 2008. 我们会让 Visual Studio 为控制器、模型和视图生成初始代码和内容。We'll let Visual Studio generate the initial code and content for our controllers, models, and views.

如果你使用的是 Active Server Pages 或 ASP.NET,则应该会发现 ASP.NET MVC 非常熟悉。If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC 视图非常类似于 Active Server Pages 应用程序中的页面。ASP.NET MVC views are very much like the pages in an Active Server Pages application. 与传统的 ASP.NET Web 窗体应用程序一样,ASP.NET MVC 为你提供 .NET framework 提供的丰富语言和类的完全访问权限。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.NET MVC 应用程序的体验与生成 Active Server Pages 或 ASP.NET Web 窗体应用程序的体验是类似的。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.

电影数据库应用程序概述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:

列出一组电影数据库记录List a set of movie database records

创建新的电影数据库记录Create a new movie database record

编辑现有的电影数据库记录Edit an existing movie database record

同样,由于我们想要简单简单,我们将利用构建应用程序所需的 ASP.NET MVC 框架的最小功能数。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.

若要创建应用程序,需要完成以下每个步骤:In order to create our application, we need to complete each of the following steps:

创建 ASP.NET MVC Web 应用程序项目Create the ASP.NET MVC Web Application Project

创建数据库Create the database

创建数据库模型Create the database model

创建 ASP.NET MVC 控制器Create the ASP.NET MVC controller

创建 ASP.NET MVC 视图Create the ASP.NET MVC views

初步操作Preliminaries

需要 Visual Studio 2008 或 Visual Web Developer 2008 Express 才能生成 ASP.NET MVC 应用程序。You'll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. 还需要下载 ASP.NET MVC 框架。You also need to download the ASP.NET MVC framework.

如果你没有 Visual Studio 2008,你可以从以下网站90下载试用版的 Visual Studio 2008: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 Web Developer Express 2008 创建 ASP.NET MVC 应用程序。Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. 如果决定使用 Visual Web Developer Express,则必须安装 Service Pack 1。If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. 你可以从此网站下载 Visual Web Developer 2008 Express Service Pack 1:You can download Visual Web Developer 2008 Express with Service Pack 1 from this website:

安装 Visual Studio 2008 或 Visual Web Developer 2008 后,需要安装 ASP.NET MVC 框架。After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. 你可以从以下网站下载 ASP.NET MVC 框架:You can download the ASP.NET MVC framework from the following website:

Note

你可以利用 Web 平台安装程序,而不是单独下载 ASP.NET framework 和 ASP.NET MVC 框架。Instead of downloading the ASP.NET framework and the ASP.NET MVC framework individually, you can take advantage of the Web Platform Installer. Web 平台安装程序是一种应用程序,使你能够轻松地管理已安装的应用程序是否为你的计算机:The Web Platform Installer is an application that enables you to easily manage the installed applications are your computer:

创建 ASP.NET MVC Web 应用程序项目Creating an ASP.NET MVC Web Application Project

首先,让我们在 Visual Studio 2008 中创建新的 ASP.NET MVC Web 应用程序项目。Let's start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. 选择菜单选项 "文件"、"新建项目",您将看到图1中的 "新建项目" 对话框。Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. 选择C#作为编程语言,然后选择 "ASP.NET MVC Web 应用程序" 项目模板。Select C# as the programming language and select the ASP.NET MVC Web Application project template. 为项目指定名称 MovieApp,然后单击 "确定" 按钮。Give your project the name MovieApp and click the OK button.

15115dc4f907cb1b8de42a15d7951c08.png15115dc4f907cb1b8de42a15d7951c08.png

图 01: "新建项目" 对话框(单击以查看完全大小的图像)Figure 01: The New Project dialog box (Click to view full-size image)

请确保从 "新建项目" 对话框顶部的下拉列表中选择 .NET Framework 3.5,否则不会出现 "ASP.NET MVC Web 应用程序" 项目模板。Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template won't appear.

每次创建新的 MVC Web 应用程序项目时,Visual Studio 都会提示您创建一个单独的单元测试项目。Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. 图2中的对话框随即出现。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.

Note

Visual Web Developer 不支持测试项目。Visual Web Developer does not support test projects.

6f838a9caaa3e1f7fd1e20d2f049e6f4.png6f838a9caaa3e1f7fd1e20d2f049e6f4.png

图 02: "创建单元测试项目" 对话框(单击以查看完全大小的图像)Figure 02: The Create Unit Test Project dialog (Click to view full-size image)

ASP.NET MVC 应用程序具有一组标准文件夹:模型、视图和控制器文件夹。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.

使用 Visual Studio 创建新的 MVC 应用程序时,将获得一个示例应用程序。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:

Controllers\HomeController.csControllers\HomeController.cs

Views\HomeViews\Home

创建数据库Creating the Database

我们需要创建一个数据库来存放电影数据库记录。We need to create a database to hold our movie database records. 幸运的是,Visual Studio 包括一个名为 SQL Server Express 的免费数据库。Luckily, Visual Studio includes a free database named SQL Server Express. 按照以下步骤创建数据库:Follow these steps to create the database:

右键单击 "解决方案资源管理器" 窗口中的 "应用_Data" 文件夹,然后选择 "添加"、"新建项" 菜单。Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.

选择 "数据" 类别,然后选择 " SQL Server" 数据库模板(请参阅图3)。Select the Data category and select the SQL Server Database template (see Figure 3).

将新数据库命名为MoviesDB ,然后单击 "添加" 按钮。Name your new database MoviesDB.mdf and click the Add button.

创建数据库后,可以通过双击位于应用_Data 文件夹中的 MoviesDB 文件来连接到数据库。After you create your database, you can connect to the database by double-clicking the MoviesDB.mdf file located in the App_Data folder. 双击 MoviesDB 文件将打开 "服务器资源管理器" 窗口。Double-clicking the MoviesDB.mdf file opens the Server Explorer window.

Note

在 Visual Web Developer 的情况下,"服务器资源管理器" 窗口称为数据库资源管理器 "窗口。The Server Explorer window is named the Database Explorer window in the case of Visual Web Developer.

98a7710a3812d70bd04f751296baa843.png98a7710a3812d70bd04f751296baa843.png

图 03:创建 Microsoft SQL Server 数据库(单击查看完全大小的映像)Figure 03: Creating a Microsoft SQL Server Database (Click to view full-size image)

接下来,需要创建一个新的数据库表。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

允许 Null 值Allow Nulls

IdId

IntInt

FalseFalse

标题Title

Nvarchar(100)Nvarchar(100)

FalseFalse

导演Director

Nvarchar(100)Nvarchar(100)

FalseFalse

DateReleasedDateReleased

DateTimeDateTime

FalseFalse

第一列(Id 列)包含两个特殊属性。The first column, the Id column, has two special properties. 首先,需要将 Id 列标记为主键列。First, you need to mark the Id column as the primary key column. 选择 Id 列后,单击 "设置主键" 按钮(它是看起来像一个键的图标)。After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). 其次,需要将 Id 列标记为标识列。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. 完成后,表应如图4所示。When you are finished, the table should look like Figure 4.

42aa5b2850caf6544797d6a0fff0213a.png42aa5b2850caf6544797d6a0fff0213a.png

图 04:电影数据库表(单击以查看完全大小的图像)Figure 04: The Movies database table (Click to view full-size image)

最后一步是保存新表。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. 输入喜欢的电影列表(见图5)。Enter a list of your favorite movies (see Figure 5).

91aa72a1f10bf385fae7f91b7c6d50c9.png91aa72a1f10bf385fae7f91b7c6d50c9.png

图 05:输入电影记录(单击以查看完全大小的图像)Figure 05: Entering movie records (Click to view full-size image)

创建模型Creating the Model

接下来,需要创建一组类以表示数据库。We next need to create a set of classes to represent our database. 我们需要创建一个数据库模型。We need to create a database model. 我们将利用 Microsoft 实体框架自动为数据库模型生成类。We'll take advantage of the Microsoft Entity Framework to generate the classes for our database model automatically.

Note

ASP.NET MVC 框架不与 Microsoft 实体框架相关联。The ASP.NET MVC framework is not tied to the Microsoft Entity Framework. 可以通过利用各种对象关系映射(或/M)工具(包括 LINQ to SQL、Subsonic 和 NHibernate)来创建数据库模型类。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.

请按照以下步骤启动实体数据模型向导:Follow these steps to launch the Entity Data Model Wizard:

右键单击 "解决方案资源管理器" 窗口中的 "模型" 文件夹,然后选择 "添加"、"新建项" 菜单。Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.

选择 "数据" 类别,然后选择 " ADO.NET 实体数据模型" 模板。Select the Data category and select the ADO.NET Entity Data Model template.

为数据模型指定名称MoviesDBModel ,并单击 "添加" 按钮。Give your data model the name MoviesDBModel.edmx and click the Add button.

单击 "添加" 按钮后,将显示 "实体数据模型" 向导(见图6)。After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). 按照以下步骤完成向导:Follow these steps to complete the wizard:

在 "选择模型内容" 步骤中,选择 "从数据库生成" 选项。In the Choose Model Contents step, select the Generate from database option.

在 "选择你的数据连接" 步骤中,使用MoviesDB数据连接,并为连接设置使用名称 " MoviesDBEntities "。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. 输入命名空间MovieApp ,并单击 "完成" 按钮。Enter the namespace MovieApp.Models and click the Finish button.

3392984a4e9e5160bbf37402e52be071.png3392984a4e9e5160bbf37402e52be071.png

图 06:使用实体数据模型向导生成数据库模型(单击以查看完全大小的图像)Figure 06: Generating a database model with the Entity Data Model Wizard (Click to view full-size image)

完成实体数据模型向导后,"实体数据模型设计器会打开。After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. 设计器应显示电影数据库表(参见图7)。The Designer should display the Movies database table (see Figure 7).

7f11356cba3efeea8a0b399c1055fa64.png7f11356cba3efeea8a0b399c1055fa64.png

图 07:实体数据模型设计器(单击查看完全尺寸的图像)Figure 07: The Entity Data Model Designer (Click to view full-size image)

在继续操作之前,我们需要进行一项更改。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. 由于我们将使用 movie 类来表示特定电影,因此我们需要将类的名称修改为电影,而不是影片(单数形式)。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).

双击设计器图面上类的名称,并将类的名称从 "电影" 更改为 "电影"。Double-click the name of the class on the designer surface and change the name of the class from Movies to Movie. 做出此更改后,单击 "保存" 按钮(软盘的图标)以生成 Movie 类。After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.

创建 ASP.NET MVC 控制器Creating the ASP.NET MVC Controller

下一步是创建 ASP.NET MVC 控制器。The next step is to create the ASP.NET MVC controller. 控制器负责控制用户如何与 ASP.NET MVC 应用程序交互。A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.

请执行这些步骤:Follow these steps:

在 "解决方案资源管理器" 窗口中,右键单击 "控制器" 文件夹,然后选择 "添加"、"控制器" 菜单。In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.

在 "添加控制器" 对话框中,输入名称HomeController ,并选中标签为 "添加" "创建"、"更新" 和 "详细信息" 方案的 "操作方法" 的复选框(见图8)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.

完成这些步骤后,会创建列表1中的控制器。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.

455d56170452277e20961794c98eaaf8.png455d56170452277e20961794c98eaaf8.png

图 08:添加新的 ASP.NET MVC 控制器(单击以查看完全大小的映像)Figure 08: Adding a new ASP.NET MVC Controller (Click to view full-size image)

列表1– Controllers\HomeController.csListing 1 – Controllers\HomeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ActionResult Index()

{

return View();

}

//

// GET: /Home/Details/5

public ActionResult Details(int id)

{

return View();

}

//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(FormCollection collection)

{

try

{

// TODO: Add insert logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

return View();

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

}

}

列出数据库记录Listing Database Records

Home 控制器的 Index ()方法是 ASP.NET MVC 应用程序的默认方法。The Index() method of the Home controller is the default method for an ASP.NET MVC application. 运行 ASP.NET MVC 应用程序时,Index ()方法是调用的第一个控制器方法。When you run an ASP.NET MVC application, the Index() method is the first controller method that is called.

我们将使用 Index ()方法显示电影数据库表中的记录列表。We'll use the Index() method to display the list of records from the Movies database table. 我们将利用之前创建的数据库模型类,通过 Index ()方法检索电影数据库记录。We'll take advantage of the database model classes that we created earlier to retrieve the movie database records with the Index() method.

我修改了清单2中的 HomeController 类,使其包含一个名为 _db 的新私有字段。I've modified the HomeController class in Listing 2 so that it contains a new private field named _db. MoviesDBEntities 类表示我们的数据库模型,我们将使用此类与数据库进行通信。The MoviesDBEntities class represents our database model and we'll use this class to communicate with our database.

我还在清单2中修改了 Index ()方法。I've also modified the Index() method in Listing 2. Index ()方法使用 MoviesDBEntities 类来检索电影数据库表中的所有电影记录。The Index() method uses the MoviesDBEntities class to retrieve all of the movie records from the Movies database table. 表达式 _db。MovieSet. System.linq.enumerable.tolist () 返回电影数据库表中所有电影记录的列表。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. 传递给 View ()方法的任何内容都将作为视图数据传递给视图。Anything that gets passed to the View() method gets passed to the view as view data.

列出2–控制器/HomeController (修改的索引方法)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());

}

}

}

Index ()方法返回一个名为 Index 的视图。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:

在打开 "添加视图" 对话框或在 "查看数据类" 下拉列表中未显示任何类之前,应生成项目(选择菜单选项 "生成"、"生成解决方案")。You should build your project (select the menu option Build, Build Solution) before opening the Add View dialog or no classes will appear in the View data class dropdown list.

在代码编辑器中右键单击 Index ()方法,然后选择菜单选项 "添加视图" (参见图9)。Right-click the Index() method in the code editor and select the menu option Add View (see Figure 9).

在 "添加视图" 对话框中,验证是否选中了标记为 "创建强类型视图" 的复选框。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.

从 "查看数据类" 下拉列表中,选择值MovieApp。From the View data class dropdown list, select the value MovieApp.Models.Movie.

单击 "添加" 按钮创建新视图(请参阅图10)。Click the Add button to create the new view (see Figure 10).

完成这些步骤后,会将名为 "Views\Home" 的新视图添加到 "" 文件夹。After you complete these steps, a new view named Index.aspx is added to the Views\Home folder. 索引视图的内容包括在列表3中。The contents of the Index view are included in Listing 3.

3602106fb3596805cc69b83b4ad1aef5.png3602106fb3596805cc69b83b4ad1aef5.png

图 09:通过控制器操作添加视图(单击查看完全大小的图像)Figure 09: Adding a view from a controller action (Click to view full-size image)

9fe2c59c3458df02246066b87c1f3b27.png9fe2c59c3458df02246066b87c1f3b27.png

图 10:使用 "添加视图" 对话框创建新视图(单击查看完全尺寸的图像)Figure 10: Creating a new view with the Add View dialog (Click to view full-size image)

列表 3-Views\Home\Index.aspxListing 3 – Views\Home\Index.aspx

>" %>

Index

Index

Id

Title

Director

DateReleased

|

"索引" 视图显示 HTML 表中电影数据库表的所有电影记录。The Index view displays all of the movie records from the Movies database table within an HTML table. 视图包含一个 foreach 循环,该循环可循环访问 ViewData 属性所表示的每个电影。The view contains a foreach loop that iterates through each movie represented by the ViewData.Model property. 如果通过按 F5 键运行应用程序,则会看到图11中的网页。If you run your application by hitting the F5 key, then you'll see the web page in Figure 11.

f4991ab3053f74ed905231db2b3915a1.pngf4991ab3053f74ed905231db2b3915a1.png

图 11: "索引" 视图(单击以查看完全大小的图像)

创建新的数据库记录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.

Home 控制器包含两个名为 Create ()的方法。The Home controller contains two methods named Create(). 第一个 Create ()方法没有参数。The first Create() method has no parameters. Create ()方法的此重载用于显示用于创建新的电影数据库记录的 HTML 窗体。This overload of the Create() method is used to display the HTML form for creating a new movie database record.

第二个 Create ()方法具有 FormCollection 参数。The second Create() method has a FormCollection parameter. 在将用于创建新电影的 HTML 表单发送到服务器时,将调用 Create ()方法的此重载。This overload of the Create() method is called when the HTML form for creating a new movie is posted to the server. 请注意,第二个 Create ()方法具有 AcceptVerbs 属性,该属性阻止调用方法,除非执行 HTTP POST 操作。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 ()方法已在清单4的更新的 HomeController 类中进行了修改。This second Create() method has been modified in the updated HomeController class in Listing 4. 新版本的 Create ()方法接受 Movie 参数,并包含用于将新电影插入到电影数据库表的逻辑。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.

Note

请注意 "绑定" 属性。Notice the Bind attribute. 由于我们不想更新 HTML 格式的电影 Id 属性,因此需要显式排除此属性。Because we don't want to update the Movie Id property from HTML form, we need to explicitly exclude this property.

列表4– Controllers\HomeController.cs (已修改的 Create 方法)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 可以轻松地创建新的电影数据库记录(见图12)。Visual Studio makes it easy to create the form for creating a new movie database record (see Figure 12). 请执行这些步骤:Follow these steps:

在代码编辑器中右键单击 Create ()方法,然后选择菜单选项 "添加视图"。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.

从 "查看数据类" 下拉列表中,选择值MovieApp。From the View data class dropdown list, select the value MovieApp.Models.Movie.

单击 "添加" 按钮创建新视图。Click the Add button to create the new view.

c923601006b743aa7b160404dc6707e3.pngc923601006b743aa7b160404dc6707e3.png

图 12:添加 "创建" 视图(单击以查看完全大小的图像)Figure 12: Adding the Create view (Click to view full-size image)

Visual Studio 会自动生成列表5中的视图。Visual Studio generates the view in Listing 5 automatically. 此视图包含一个 HTML 窗体,其中包含与 Movie 类的每个属性对应的字段。This view contains an HTML form that includes fields that correspond to each of the properties of the Movie class.

列表5– Views\Home\Create.aspxListing 5 – Views\Home\Create.aspx

" %>

Create

Create

Fields

Id:

Title:

Director:

DateReleased:

Note

"添加视图" 对话框生成的 HTML 窗体将生成一个 Id 窗体字段。The HTML form generated by the Add View dialog generates an Id form field. 由于 Id 列是标识列,因此不需要此窗体字段,你可以安全地将其删除。Because the Id column is an Identity column, we don't need this form field and you can safely remove it.

添加 "创建" 视图后,可以将新的电影记录添加到数据库中。After you add the Create view, you can add new Movie records to the database. 按 F5 键运行应用程序,并单击 "新建" 链接以查看图13中的窗体。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.

c0d25e7cb880857fe6cda1d6479bf2d9.pngc0d25e7cb880857fe6cda1d6479bf2d9.png

图 13:创建新的电影数据库记录(单击以查看完全大小的图像)Figure 13: Creating a new movie database record (Click to view full-size image)

编辑现有的数据库记录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. 此步骤很简单,因为 Visual Studio 会自动为我们生成编辑窗体。This step is easy since Visual Studio will generate the Edit form for us automatically. 在 Visual Studio 代码编辑器中打开 HomeController.cs 类,然后执行以下步骤:Open the HomeController.cs class in the Visual Studio code editor and follow these steps:

右键单击代码编辑器中的 Edit ()方法,然后选择 "添加视图" 菜单选项(见图14)。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.

从 "查看数据类" 下拉列表中,选择值MovieApp。From the View data class dropdown list, select the value MovieApp.Models.Movie.

单击 "添加" 按钮创建新视图。Click the Add button to create the new view.

完成这些步骤后,会将名为 "Views\Home" 的新视图添加到 "" 文件夹。Completing these steps adds a new view named Edit.aspx to the Views\Home folder. 此视图包含用于编辑电影记录的 HTML 窗体。This view contains an HTML form for editing a movie record.

3e503f7e3d64ac8e86ae5091e2abc6ab.png3e503f7e3d64ac8e86ae5091e2abc6ab.png

图 14:添加编辑视图(单击以查看完全大小的图像)Figure 14: Adding the Edit view (Click to view full-size image)

Note

编辑视图包含与 "电影 Id" 属性相对应的 HTML 表单域。The Edit view contains an HTML form field that corresponds to the Movie Id property. 由于不希望用户编辑 Id 属性的值,因此应删除此窗体字段。Because you don't want people editing the value of the Id property, you should remove this form field.

最后,我们需要修改 Home 控制器,使其支持编辑数据库记录。Finally, we need to modify the Home controller so that it supports editing a database record. 已更新的 HomeController 类包含在列表6中。The updated HomeController class is contained in Listing 6.

清单6– Controllers\HomeController.cs (编辑方法)Listing 6 – Controllers\HomeController.cs (Edit methods)

//

// 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");

}

在列表6中,我已将其他逻辑添加到了 Edit ()方法的两个重载。In Listing 6, I've added additional logic to both overloads of the Edit() method. 第一个 Edit ()方法返回与传递给该方法的 Id 参数相对应的电影数据库记录。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.

请注意,必须检索原始电影,然后调用 ApplyPropertyChanges ()来更新数据库中的现有电影。Notice that you must retrieve the original movie, and then call ApplyPropertyChanges(), to update the existing movie in the database.

摘要Summary

本教程的目的是让你了解构建 ASP.NET MVC 应用程序的体验。The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. 我希望您发现生成 ASP.NET MVC web 应用程序的过程与生成 Active Server Pages 或 ASP.NET 应用程序的体验非常类似。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.

在本教程中,我们仅检查了 ASP.NET MVC 框架的最基本功能。In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. 在将来的教程中,我们将深入探讨控制器、控制器操作、视图、视图数据和 HTML 帮助器等主题。In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值