65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET MVC 中集成 JqGrid 的 Qtip

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4投票s)

2011 年 11 月 16 日

CPOL

2分钟阅读

viewsIcon

40352

downloadIcon

1276

如何在 ASP.MVC 应用程序中集成 Qtip 与 JqGrid

引言

在本文中,我将通过代码示例演示如何在 ASP.MVC 应用程序中集成 qtip 与 JqGrid。 这是一种通用的实现方式,您只需在 ColModel 中设置一个名为“description”的自定义属性,将其设置为要在工具提示中显示的内容,例如文本、图像和服务器端数据等。

为了有效地理解这个例子,我假设您具备 JqGrid (http://www.trirand.com/blog/)、QTip (http://craigsworks.com/projects/qtip/) 和 ASP.NET MVC (http://www.asp.net/mvc) 的基本知识。

创建一个新的 ASP.NET MVC 应用程序

在 Visual Studio 2010 sp1 中,转到:文件 -> 项目 ->

File-New.png

在 Visual C# 下选择“Web”,然后选择 ASP.NET MVC 3 Web 应用程序,并将解决方案的名称更改为“JqGridWithQTipIntegration”。

Create-solution_small.png

在下一步中,让选项保持默认状态,选择“Internet 应用程序”和“视图引擎为 .aspx”。

单击“确定”按钮以创建一个新的 ASP.NET MVC 3 Web 应用程序。

nextstp-creation.png

项目创建后,您将在解决方案资源管理器中看到以下层次结构。

solution-hrchy.png

构建一个用于演示的自定义模型

在 ASP.NET MVC Web 应用程序的 model 文件夹中,添加名为“SomeEntity.cs”和“Repository.cs”的新类。

SomeEntity.cs

  public class SomeEntity
    {
        public int Id { get; set; }
        public int IntProperty { get; set; }
        public string StringProperty { get; set; }
        public DateTime DateProperty { get; set; }
    }

Repository.cs

/// <summary>
/// Trivial repository of random data for demo purposes. 
/// Not for use in a real application!
/// </summary>
    public class Repository
    {
        private static IQueryable<SomeEntity> _data;

        public IQueryable<SomeEntity> SelectAll()
        {
            return _data;
        }

        /// <summary>
        /// Demo data is static so that we can demonstrate sorting with the 
        /// same data for the whole lifetime of the application.
        /// </summary>
        static Repository()
        {
            var data = new List<SomeEntity>();
            var rand = new Random();
            for (int i = 0; i < 100; i++)
            {
                data.Add(new SomeEntity
                    {
                        Id = i,
                        IntProperty = rand.Next(99),
                        StringProperty = rand.Next(99).ToString(),
                        DateProperty = new DateTime(2000 + rand.Next(10), 
                        	rand.Next(11) + 1, rand.Next(27) + 1)
                    });
            }
            _data = data.AsQueryable();
        }
    }

在 HomeController 中添加 ActionMethod,该方法将返回 JqGrid 的服务器端数据

在 Home Controller 中添加以下 Action 方法。 这将返回服务器端数据以绑定 JqGrid,其类型为 Json,并且它将接收 JqGrid 通过 ajax 请求发送的参数,如下所示。

(jqgrid 默认参数与 ajax 请求的链接)

public ActionResult GridDemoData(int page, int rows, 
		string search, string sidx, string sord)
        {
            int currentPage = Convert.ToInt32(page) - 1;
            int totalRecords = 0;
            var repository = new Repository();
            var data = repository.SelectAll();
            totalRecords = data.Count();
            var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,

                rows = (
                           from m in data
                           select new
                           {
                               id = m.Id,
                               cell = new object[]
                                      {
                                          m.IntProperty,
                                          m.StringProperty,
                                          String.Format("{0:MM/dd/yyyy}", m.DateProperty)
                                      }
                           }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

JqGrid 和 Qtip 设置要求

您需要在 Site.Master 中包含以下文件以实现该解决方案

  • ui.jqgrid.css 用于 jqgrid 样式和格式化
  • jquery-ui-1.8.custom.css 用于样式和格式化
  • jquery-1.5.1.min.js 用于 jquery 框架
  • jquery-ui-1.8.7custom.min.js 用于 jquery UI,例如对话框等。
  • grid.locale-en.js 用于 jqgrid 本地化
  • jquery.jqGrid.min.js 是 jqgrid 所必需的
<link href="<%= ResolveUrl("~/Content/themes/redmond/ui.jqgrid.css") %>" rel="stylesheet"
        type="text/css" />
    <link href="<%= ResolveUrl("~/Content/Site.css") %>" 
		rel="stylesheet" type="text/css" />
    <link href="<%= ResolveUrl("~/Content/themes/redmond/jquery-ui-1.8.custom.css") %>"
        rel="stylesheet" type="text/css" />
    <script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js") %>" 
		type="text/javascript">
    </script>
    <script src="../../Scripts/jquery-ui-1.8.7custom.min.js" 
		type="text/javascript"></script>
    <script src="../../Scripts/grid.locale-en.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>

注意:包含文件的顺序很重要,因为如果您更改顺序,则 JqGrid 将无法正常运行。

JqGrid 配置

以下是 JqGrid 的 JavaScript 和 HTML 代码。

Index.aspx 中添加的 HTML 元素用于 JqGrid

<table id="grid" cellpadding="0" cellspacing="0">
        </table>
        <div id="pager" style="text-align: center;">
        </div>
        <div id="search" style="margin-left: 30%; display: none">
        </div>

JqGrid 在 Home.GridDemo.js 中的 JavaScript 代码

var lastsel;
$(function () {

    $("#grid").jqGrid({
        colNames: ['Int', 'String', 'Date'],
        colModel: [
                        { name: 'IntProperty', index: 'IntProperty', sortable: true,
                            editable: true, editoptions: { dataInit: ShowHint },
                            description: 'IntProperty tooltip goes here'
                        },
                        { name: 'StringProperty', index: 'StringProperty', sortable: true,
                            editable: true, editoptions: { dataInit: ShowHint },
                            description: 'StringProperty tooltip goes here'
                        },
                        { name: 'DateProperty', index: 'DateProperty', sortable: true,
                            editable: true, editoptions: { dataInit: ShowHint },
                            description: 'DateProperty tooltip goes here'
                        },
                      ],
        pager: $("#pager"),
        sortname: 'IntProperty',
        rowNum: 10,
        rowList: [10, 20, 50],
        sortorder: "",
        height: 300,
        imgpath: '/Content/jqGridCss/redmond/images',
        width: 800,
        url: "/Home/GridDemoData",
        datatype: 'json',
        mtype: 'GET',
        onCellSelect: function (rowid, iCol, aData) {

            if (rowid && rowid !== lastsel) {

                if (lastsel)
                    jQuery('#grid').jqGrid('restoreRow', lastsel);
                jQuery('#grid').jqGrid('editRow', rowid, true);
                lastsel = rowid;
            }
        }
    }).navGrid($("#pager"), { edit: true, add: false, del: false, search: false });
    $("#search").filterGrid($("#grid"), {
        gridModel: false,
        filterModel: [{
            label: 'Search',
            name: 'search',
            stype: 'text'
        }]
    });
});

请注意,“description”是一个自定义属性,其中包含工具提示的文本,并且调用“ShowHint”方法以将描述文本显示为工具提示。

JqGrid 与 QTip 集成的通用实现

以下是 JqGrid 与 Qtip 集成的代码,位于 Helper.js

// this function show tool tip dialog for a certain element of 
// jqgrid and assumes that jqgrid name is #grid
function ShowHint(elem) {
    var selector = '';
 
    if (this.gridName != null)
        selector = '#' + this.gridName;
    else if ($('#grid') != null) {
        selector = '#grid';
    }

    if (selector == '') {
        alert('jqgrid name is not "grid" or gridName "Edit Option" not set');
        return;
    }

    if (elem == 0)
        return;

    jQuery(elem).qtip({
        content: getColDescription(this.name, selector),
        show: 'focusin',
        hide: 'focusout',
        style:
    {
        name: 'red',
        tip: 'leftTop',
        textAlign: 'left',
        fontWeight: '500',
        fontSize: '11px'
    },
        position:
    {
        corner:
        {
            target: 'rightTop',
            tooltip: 'LeftTop'

        }
    }
    });
}

function getColDescription(colName, jqGridSelector) {
    var description = '';
    if (colName != '') {
        var colModel = $(jqGridSelector).getGridParam('colModel');
        $.each(colModel, function (index, model) {
            if (model.name == colName) {
                description = model.description;
                return false;
            }

        });
    }

    return description;
}

Web 页面工作示例

webPage_small.png

您可以下载提供的链接中的完整演示代码。

© . All rights reserved.