使用表格显示数据库中的数据

Displaying a Table of Database Data

The goal of this tutorial is to explain how you can display an HTML table of database data in an ASP.NET MVC application. First, you learn how to use the scaffolding tools included in Visual Studio to generate a view that displays a set of records automatically. Next, you learn how to use a partial as a template when formatting database records.

  这篇教程的目的是讲解如何在ASP.NET MVC应用程序中使用HTML表格显示数据库中数据。首先,你将学会如何使用Visual Studio自带的支架工具自动生成一个View来显示一个记录集。接下来,你将学习如何使用一个局部页面模板格式化显示数据库的记录。

Create the Model Classes

We are going to display the set of records from the Movies database table. The Movies database table contains the following columns:

  我们将要做的是显示Movies 数据表中的记录集,Movies 数据表包含了以下的列:

Column Name Data Type Allow Nulls
Id Int False
Title Nvarchar(200) False
Director NVarchar(50) False
DateReleased DateTime False

In order to represent the Movies table in our ASP.NET MVC application, we need to create a model class. In this tutorial, we use the Microsoft Entity Framework to create our model classes.

In this tutorial, we use the Microsoft Entity Framework. However, it is important to understand that you can use a variety of different technologies to interact with a database from an ASP.NET MVC application including LINQ to SQL, NHibernate, or ADO.NET.

  为了在 ASP.NET MVC应用程序中表示Movies表,我们需要创建一个模型类,在这篇教程,我们使用 Microsoft Entity Framework 来创建我们的模型类。

  在这篇教程,我们使用 Microsoft Entity Framework 。然而,重要的是你要理解在ASP.NET MVC应用程序中你可以使用不同的技术包括LINQ to SQL, NHibernate, 或者ADO.NET来与数据库进行交互。

 

Follow these steps to launch the Entity Data Model Wizard:

  1. Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.
  2. Select the Data category and select the ADO.NET Entity Data Model template.
  3. Give your data model the name MoviesDBModel.edmx and click the Add button.

请按照以下的步骤来启动实体数据模型向导:

  1. 在解决方案资源管理器窗口中,右键单击Models文件夹,选择菜单“添加”,“添加新项”。
  2. 选择类别数据,然后选择ADO.NET Entity Data Model 模板。
  3. 给你的数据模型命名为MoviesDBModel.edmx ,然后点击添加按钮。

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

  1. In the Choose Model Contents step, select the Generate from database option.
  2. 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.
  3. In the Choose Your Database Objects step, expand the Tables node, select the Movies table. Enter the namespace Models and click the Finish button.

当你点击添加按钮后,实体数据模型向导将会出现,按照这些步骤来完成该向导:

  1. 在选择模型内容这一步,选择从数据库中生成选项。
  2. 在选择您的数据连接这一步,使用MoviesDB.mdf 数据连接,然后给数据连接配置命名为MoviesDBEntities
  3. 在选择数据库对象这一步,展开表节点,选择Movies表,输入模型的命名空间,点击完成按钮。

Figure 01: Creating LINQ to SQL classes (Click to view full-size image)

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

  当你完成数据实体模型向导后,将会打开数据实体模型设计器。显示Movies的实体。

Figure 02: 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. 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. After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.

  在继续之前,我们需要做个一个修改,实体数据模型向导生成了一个表示Movies数据表的Movies 类,由于我们将要使用Movies类表示一个movie集合,所以我们需要修改类的名称为Movie(单数而不是复数)

  双击设计器的表面类的名称,将类的名称从Movies改为Movie。完成此更改后,点击保存按钮(软盘图标)来生成Movie类。

Create the Movies Controller

Now that we have a way to represent our database records, we can create a controller that returns the collection of movies. Within the Visual Studio Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller (see Figure 3).

  现在我们有两种办法来表示我们数据库中的记录,我们可以创建一个Controller来返回一个movies集合。在Visual Studio解决方案资源管理器窗口中,右键单击Controllers 文件夹,选择菜单选项添加,Controller(见图3)。

Figure 03: The Add Controller Menu (Click to view full-size image)

When the Add Controller dialog appears, enter the controller name MovieController (see Figure 4). Click the Add button to add the new controller.

  在弹出Add Controller对话框的时候,输入控制器的名称为MovieController(见图4),单击Add按钮来添加新的控制器。

Figure 04: The Add Controller dialog(Click to view full-size image)


We need to modify the Index() action exposed by the Movie controller so that it returns the set of database records. Modify the controller so that it looks like the controller in Listing 1.

  我们需要公开Movie controller 的Index()的动作,以便它返回一个数据库的记录集。按照清单1修改控制器的代码。

Listing 1 – Controllers\MovieController.cs

using System.Linq;

using System.Web.Mvc;

using MvcApplication1.Models; 

namespace MvcApplication1.Controllers

{

    public class MovieController : Controller

    {

        //

        // GET: /Movie/ 

        public ActionResult Index()

        {

            var entities = new MoviesDBEntities();

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

        } 

    }

}

In Listing 1, the MoviesDBEntities class is used to represent the MoviesDB database. To use this class, you need to import the MvcApplication1.Models namespace like this:

using MvcApplication1.Models;

The expression entities.MovieSet.ToList() returns the set of all movies from the Movies database table.

 

  在代码清单1中,类MoviesDBEntities用来表示MoviesDB数据库,要使用这个类,你需要导入这样导入MvcApplication1.Models命名空间:

using MvcApplication1.Models;

  表达式 entities.MovieSet.ToList() 将返回Movies数据表中的所有电影的集合。

Create the View

The easiest way to display a set of database records in an HTML table is to take advantage of the scaffolding provided by Visual Studio.

Build your application by selecting the menu option Build, Build Solution. You must build your application before opening the Add View dialog or your data classes won’t appear in the dialog.

Right-click the Index() action and select the menu option Add View (see Figure 5).

  用HTML表格显示将数据库的记录集的最简单的方法是利用Visual Studio的支架。选择菜单生成,重新生成解决方案来重新生成你的应用程序,比必须在打开Add View对话框前重新生成你的应用程序,否则你的数据模型类将不会出现在对话框中。

 

Figure 05: Adding a view (Click to view full-size image)

In the Add View dialog, check the checkbox labeled Create a strongly-typed view. Select the Movie class as the view data class. Select List as the view content (see Figure 6). Selecting these options will generate a strongly-typed view that displays a list of movies.

  在Add View对话框中,选中Create a strongly-typed view复选框,选择Movie类作为 view data class,选择List作为View Content。通过这些选项将生成一个现实movies集合的强类型的View。

 

Figure 06: The Add View dialog(Click to view full-size image)

After you click the Add button, the view in Listing 2 is generated automatically. This view contains the code required to iterate through the collection of movies and display each of the properties of a movie.

  当你点击Add按钮后,清单2中View的代码将自动生成。这个View包含了你需要遍历movies集合以及movie的每一个属性的代码。

Listing 2 – Views\Movie\Index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

      Index

</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <h2>Index</h2> 

    <table>

        <tr>

            <th></th>

            <th>

                Id

            </th>

            <th>

                Title

            </th>

            <th>

                Director

            </th>

            <th>

                DateReleased

            </th>

        </tr> 

    <% foreach (var item in Model) { %>

   

        <tr>

            <td>

                <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |

                <%= Html.ActionLink("Details", "Details", new { id=item.Id })%>

            </td>

            <td>

                <%= Html.Encode(item.Id) %>

            </td>

            <td>

                <%= Html.Encode(item.Title) %>

            </td>

            <td>

                <%= Html.Encode(item.Director) %>

            </td>

            <td>

                <%= Html.Encode(String.Format("{0:g}", item.DateReleased)) %>

            </td>

        </tr>

   

    <% } %> 

    </table> 

    <p>

        <%= Html.ActionLink("Create New", "Create") %>

    </p> 

</asp:Content>

You can run the application by selecting the menu option Debug, Start Debugging (or hitting the F5 key). Running the application launches Internet Explorer. If you navigate to the /Movie URL then you’ll see the page in Figure 7.

  你可以通过选择菜单调试,启动调试(或者按F5键)来运行应用程序,应用程序将在Internet Explorer中启动。如果您链接到/Movie URL,那么你会看到图7的页面。

Figure 07: A table of movies(Click to view full-size image)

If you don’t like anything about the appearance of the grid of database records in Figure 7 then you can simply modify the Index view. For example, you can change the DateReleased header to Date Released by modifying the Index view.

  如果你不喜欢图7中显示数据库记录的网格外观,您可以简单地修改Index View。例如,您可以在Index View中将网格的列头DateReleased修改为Date Released

Create a Template with a Partial

When a view gets too complicated, it is a good idea to start breaking the view into partials. Using partials makes your views easier to understand and maintain. We’ll create a partial that we can use as a template to format each of the movie database records.

Follow these steps to create the partial:

  1. Right-click the Views\Movie folder and select the menu option Add View.
  2. Check the checkbox labeled Create a partial view (.ascx).
  3. Name the partial MovieTemplate.
  4. Check the checkbox labeled Create a strongly-typed view.
  5. Select Movie as the view data class.
  6. Select Empty as the view content.
  7. Click the Add button to add the partial to your project. 

After you complete these steps, modify the MovieTemplate partial to look like Listing 3.

  

  当视图变得太复杂,将View分成不同的局部页面是一个不错的想法。使用局部页面将使你的视图更容易理解和维护。我们将创建一个部分页面,可以用它当做格式化Moive数据库记录的模板。 

请按照下列步骤创建局部页面:

  1. 右键单击Views\Movie 文件夹,选择菜单选项添加,视图。
  2. 选中Create a partial view (.ascx)复选框。
  3. 给局部页面命名为MovieTemplate
  4. 选中Create a strongly-typed view复选框。
  5. 选择Movie作为view data class
  6. 选中Empty作为view content
  7. 单击Add按钮,将局部页面添加到你的项目中。

  当你完成上面的步骤后,按照代码清单3那样修改MovieTemplate 局部页面。

 

Listing 3 – Views\Movie\MovieTemplate.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcApplication1.Models.Movie>" %> 

<tr>

    <td>

        <%= Html.Encode(Model.Id) %>

    </td>

    <td>

        <%= Html.Encode(Model.Title) %>

    </td>

    <td>

        <%= Html.Encode(Model.Director) %>

    </td>

    <td>

        <%= Html.Encode(String.Format("{0:g}", Model.DateReleased)) %>

    </td>

</tr>

The partial in Listing 3 contains a template for a single row of records.

The modified Index view in Listing 4 uses the MovieTemplate partial.

Listing 4 – Views\Movie\Index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <h2>Index</h2> 

    <table>

        <tr>

            <th>

                Id

            </th>

            <th>

                Title

            </th>

            <th>

                Director

            </th>

            <th>

                DateReleased

            </th>

        </tr> 

    <% foreach (var item in Model) { %>

   

        <% Html.RenderPartial("MovieTemplate", item); %>

   

    <% } %> 

    </table> 

</asp:Content>

The view in Listing 4 contains a foreach loop that iterates through all of the movies. For each movie, the MovieTemplate partial is used to format the movie. The MovieTemplate is rendered by calling the RenderPartial() helper method.

The modified Index view renders the very same HTML table of database records. However, the view has been greatly simplified.

The RenderPartial() method is different than most of the other helper methods because it does not return a string. Therefore, you must call the RenderPartial() method using <% Html.RenderPartial(); %> instead of <%= Html.RenderPartial(); %>.

  在代码清单4中View包含了以个foreach循环来遍历所有的movies,对于每个movie,MovieTemplate局部页面都会被用来格式化这个movie。MovieTemplate通过调用RenderPartial()的辅助方法来呈现。

  经过修改的Index View用相同的HTML表格来呈现数据库记录,然而,这个View已经变得非常简单了。

  与大多数其他帮助方法不同,Html.RenderPartial()方法并不会返回一个字符串。因此,你不能这样:<%= Html.RenderPartial(); %>调用RenderPatial()方法,你必须这样:<% Html.RenderPartial(); %>调用RenderPatial()方法。

Summary

The goal of this tutorial was to explain how you can display a set of database records in an HTML table. First, you learned how to return a set of database records from a controller action by taking advantage of the Microsoft Entity Framework. Next, you learned how to use Visual Studio scaffolding to generate a view that displays a collection of items automatically. Finally, you learned how to simplify the view by taking advantage of a partial. You learned how to use a partial as a template so that you can format each database record.

  这篇教程的目的是讲解如何使用HTML表格显示数据库中记录集。首先,你将学会如何利用Microsoft Entity Framework通过Controller返回一系列数据库记录。接下来,你学会了如何使用Visual Studio支架自动生成一个View来显示items集合。最后,你学会了利用局部页面来简化View,学会了如何使用局部页面模板来格式化每一条数据库记录。

 

posted @ 2009-12-15 21:52  supperwu  阅读(5158)  评论(0编辑  收藏  举报