且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【初学者指南】在ASP.NET MVC 5中创建GridView

更新时间:2022-09-21 15:25:31

介绍

在这篇文章中,我们将会学习如何在 ASP.NET MVC 中创建一个 gridview,就像 ASP.NET Web 表单中的 gridview 一样。服务器端和客户端有许多可用的第三方库,这些库能够提供所有必需的功能,如 Web 表格中的搜索、排序和分页等。是否包含这些功能,取决于应用的特殊需求,例如在客户端和服务器端提供搜索或其它功能的需求等。

可用的库

以下是一些可用的库和插件:

  • Grid.Mvc

  • MVCGrid.NET

  • PagedList.MVC

  • JQuery.Grid

  • JQuery Grid for ASP.NET MVC

  • JQuery DataTables

使用 jQuery 数据表

以上库和插件都有自己的优缺点,其中 jQuery 数据表是个不错的选择。它具有高度的灵活性,支持分页,即时搜索,多列排序;它也支持几乎所有可以被绑定的数据源。

例如:

  • DOM

  • JavaScript的

  • Ajax

  • Server-side processing

我最喜欢的选项之一是, jQuery 数据表不但支持客户端搜索、分页、排序等,而且还提供了一个可以在服务器端处理的选项。例如,一种情景是:因为数据库中有太多的数据,所以在客户端的进行分页并不是一个好选择。表格中有百万行数据,如果用客户端分页功能来绑定,页面就会由于大量的数据行处理和HTML渲染而反应很迟钝。

下面,我们先来看看一个利用客户端处理的例子。我们将会实现一个具有搜索、排序和分页功能的工作表,正如下图中我们看到的:

【初学者指南】在ASP.NET MVC 5中创建GridView

首先,我们创建将会用到的数据库和表格,打开 SQL Management Studio 并运行以下脚本:

CREATE DATABASE [GridExampleMVC] 
 GO 
 CREATE TABLE [dbo].[Assets] ( 
     [AssetID]                   UNIQUEIDENTIFIER NOT NULL, 
     [Barcode]                   NVARCHAR (MAX)   NULL, 
     [SerialNumber]              NVARCHAR (MAX)   NULL, 
     [FacilitySite]              NVARCHAR (MAX)   NULL, 
     [PMGuide]                   NVARCHAR (MAX)   NULL, 
     [AstID]                     NVARCHAR (MAX)   NOT NULL, 
     [ChildAsset]                NVARCHAR (MAX)   NULL, 
     [GeneralAssetDescription]   NVARCHAR (MAX)   NULL, 
     [SecondaryAssetDescription] NVARCHAR (MAX)   NULL, 
     [Quantity]                  INT              NOT NULL, 
     [Manufacturer]              NVARCHAR (MAX)   NULL, 
     [ModelNumber]               NVARCHAR (MAX)   NULL, 
     [Building]                  NVARCHAR (MAX)   NULL, 
     [Floor]                     NVARCHAR (MAX)   NULL, 
     [Corridor]                  NVARCHAR (MAX)   NULL, 
     [RoomNo]                    NVARCHAR (MAX)   NULL, 
     [MERNo]                     NVARCHAR (MAX)   NULL, 
     [EquipSystem]               NVARCHAR (MAX)   NULL, 
     [Comments]                  NVARCHAR (MAX)   NULL, 
     [Issued]                    BIT              NOT NULL, 
     CONSTRAINT [PK_dbo.Assets] PRIMARY KEY CLUSTERED ([AssetID] ASC) 
 ) 
 GO

源码中附有完整的 SQL 脚本,你可以利用它使用样例中的数据来创建数据库和表单。

现在,创建一个新的 ASP.NET MVC 5 Web 应用程序。打开 Visual Studio 2015,点击文件>>新建>>项目。

【初学者指南】在ASP.NET MVC 5中创建GridView

从对话框中跳转到 Web,选择 ASP.NET Web 应用程序项目,然后单击确定。

【初学者指南】在ASP.NET MVC 5中创建GridView

在模板中选择 MVC,如果编写了应用的单元测试,请先做检查,并点击 OK。

我们的工程都是用基本的功能创建的。现在,我们开始创建数据库上下文类,这个类将会被 Data Access 实体框架使用。

首先,我们需要为 Asset 表创建一个模型,我们将会使用这个模型通过 ORM 来恢复数据。

在模型文件夹中,创建一个名为 Asset 的新类:

using System.ComponentModel.DataAnnotations;namespace GridExampleMVC.Models
{    public class Asset
    {        public System.Guid AssetID { get; set; }
        [Display(Name = "Barcode")]        public string Barcode { get; set; }
        [Display(Name = "Serial-Number")]        public string SerialNumber { get; set; }
        [Display(Name = "Facility-Site")]        public string FacilitySite { get; set; }
        [Display(Name = "PM-Guide-ID")]        public string PMGuide { get; set; }
        [Required]
        [Display(Name = "Asset-ID")]        public string AstID { get; set; }
        [Display(Name = "Child-Asset")]        public string ChildAsset { get; set; }
        [Display(Name = "General-Asset-Description")]        public string GeneralAssetDescription { get; set; }
        [Display(Name = "Secondary-Asset-Description")]        public string SecondaryAssetDescription { get; set; }        public int Quantity { get; set; }
        [Display(Name = "Manufacturer")]        public string Manufacturer { get; set; }
        [Display(Name = "Model-Number")]        public string ModelNumber { get; set; }
        [Display(Name = "Main-Location (Building)")]        public string Building { get; set; }
        [Display(Name = "Sub-Location 1 (Floor)")]        public string Floor { get; set; }
        [Display(Name = "Sub-Location 2 (Corridor)")]        public string Corridor { get; set; }
        [Display(Name = "Sub-Location 3 (Room No)")]        public string RoomNo { get; set; }
        [Display(Name = "Sub-Location 4 (MER#)")]        public string MERNo { get; set; }
        [Display(Name = "Sub-Location 5 (Equip/System)")]        public string EquipSystem { get; set; }        public string Comments { get; set; }        public bool Issued { get; set; }
    }
}

现在从解决方案资源管理器跳转到模型文件夹,并打开 IdentityModels.cs 文件。我们将在数据库上下文中为 Asset 表添加一个属性,这个属性将会成为 Asset 表的实体框架表示,用它来创建脚本。在 ApplicationDbContext 类中添加新的属性:

public class ApplicationDbContext : IdentityDbContext<applicationuser>{    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {

    }    public DbSet<asset> Assets { get; set; }    public static ApplicationDbContext Create()
    {        return new ApplicationDbContext();
    }
}

以上是 ASP.NET identity 2.0 的默认实体框架设置,我们通过为 Asset 表添加新的 DbSet 来扩展它。

现在,在控制器文件夹中添加一个空的名为 AssetController 的控制器,这个控制器件将用于所有 Asset 的相关工作。

public class AssetController : Controller
    {        // GET: Asset
        public ActionResult Index()
        {            return View();
        }
    }

现在我们需要安装用于创建表格的 JQuery DataTables,进入Tools >> NuGet Package Manager >> Manage Nuget Packages for Solution,并点击它。

【初学者指南】在ASP.NET MVC 5中创建GridView

安装包管理器默认是打开的,它会在你的解决方案中显示成已安装的 nugget 包,点击浏览按钮,然后搜索 JQuery DataTables 包,选择它并检查已安装了 JQuery DataTables 的项目解决方案。在我们的案例里,我们将会以每一个需求的方式将其安装在 GridExampleMVC web 中,然后点击安装按钮。

【初学者指南】在ASP.NET MVC 5中创建GridView

Visual Studio 将会提示是否要修改解决方案,你需要点击 Ok 来继续安装 JQuery DataTables 包。

在 nugget 包安装成功后,我们需要在视图中引入 jQuery DataTables 的必要的 JS 和 CSS,为此,我们需要注册 jQuery DataTables,请打开位于 App_Start 文件夹中的 BundleConfig.cs 文件并在 CSS 和 JS 文件的结尾处添加以下代码:

bundles.Add(new ScriptBundle("~/bundles/datatables").Include(                        "~/Scripts/DataTables/jquery.dataTables.min.js",                        "~/Scripts/DataTables/dataTables.bootstrap.js"));

bundles.Add(new StyleBundle("~/Content/datatables").Include(          "~/Content/DataTables/css/dataTables.bootstrap.css"));

在为数据表添加了脚本和 CSS 之后,我们需要在总体布局中添加它们,默认情况下, _Layout.cshtml 位于 Views >> Shared 中,_ViewStart.cshtml 也默认位于这里。

【初学者指南】在ASP.NET MVC 5中创建GridView

在写控制器代码之前,我们需要为实体框架配置连接字符串,以便在操作数据库时来连接数据库。因此,我们的连接字符串应该被指定给一个有效的数据源,以便我们在运行时应用不会被打断。

为了做到这一点,请打开 web.config 并为数据库提供连接字符串。在配置文件中,你会发现下面配置节点中的连接字符串,你需要在节点中根据你的系统来修改连接字符串。

<connectionstrings>

    <add connectionstring="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=GridExampleMVC;
     Integrated Security=True;MultipleActiveResultSets=true" name="DefaultConnection"
     providername="System.Data.SqlClient"/>

</connectionstrings>

现在,请在控制器中添加数据库上下文的属性,以便我们能够在数据库中执行请求。

private ApplicationDbContext _dbContext;public ApplicationDbContext DbContext
{    get
    {        return _dbContext ?? HttpContext.GetOwinContext().Get<applicationdbcontext>();
    }    private set
    {
        _dbContext = value;
    }
}

我们将会在任何需要的控制器行为中,使用这个属性查询数据库。

在检索行为中,我们将简单地获取该表中的所有行,并将其传递给 view:

public ActionResult Index()
{    return View(DbContext.Assets.ToList());
}

我们完整的 controller 类代码,就像这样:

using GridExampleMVC.Models;using System.Linq;using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;namespace GridExampleMVC.Controllers
{    public class AssetController : Controller
    {        private ApplicationDbContext _dbContext;        public ApplicationDbContext DbContext
        {            get
            {                return _dbContext ?? HttpContext.GetOwinContext().Get<applicationdbcontext>();
            }            private set
            {
                _dbContext = value;
            }
        }        public AssetController()
        { 

        }        public AssetController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }        // GET: Asset
        public ActionResult Index()
        {            return View(DbContext.Assets.ToList());
        }
    }
}

现在来到视图部分,在视图部分中我们将会编写如何以 HTML 实现渲染的代码,请为检索行为创建一个空模板(没有模型)的视图,然后在其中添加如下代码:

@model IEnumerable< GridExampleMVC.Models.Asset>
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">Assets</h1>
            </div>
            <div class="panel-body">
                <table id="assets-data-table"
                class="table table-striped table-bordered"
                 style="width:100%">
                    <thead>
                        <tr>
                            <th>Bar Code</th>
                            <th>Manufacturer</th>
                            <th>Model Number</th>
                            <th>Building</th>
                            <th>Room No</th>
                            <th>Quantity</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var asset in Model)
                        {                            <tr>
                                <td>@asset.Barcode</td>
                                <td>@asset.Manufacturer</td>
                                <td>@asset.ModelNumber</td>
                                <td>@asset.Building</td>
                                <td>@asset.RoomNo</td>
                                <td>@asset.Quantity</td>
                            </tr>
                        }                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>@section Scripts
{   
 <script type="text/javascript">
     $(document).ready(function () {
         $('#assets-data-table').DataTable();
     });    </script>
 }

现在运行这个应用程序,你会看具有可用的排序、搜索和过滤功能的表格。但是现在还有一个问题,那就是这是在客户端处理的,当行为被调用时,所有数据会被视图渲染,这样就会造成当大量数据出现时,页面性能变慢或者页面载入时间增加。

在下一篇文章中,我们将会学习到如何通过使用服务器端分页、排序和过滤来使页面呈现的更好。对于具有大量的数据时,这是一个更好的方法。

通过本文的介绍,希望大家能够掌握在 ASP.NET MVC 5 中创建 GridView 的方法。表格控件是项目开发中经常用到的控件,其中以性能著称的是FlexGrid表格控件,这是一款轻量级的高性能表格控件,加载和滚动速度比竞争对手快10倍以上,能提供丰富的功能集,而不膨胀核心控件。



本文转自 powertoolsteam 51CTO博客,原文链接:http://blog.51cto.com/powertoolsteam/1873041,如需转载请自行联系原作者