自定义模板列在JQGrid中不起作用

时间:2011-07-07 09:19:56

标签: asp.net-mvc-3 jqgrid

专家,

我有自定义模板列的JQGrid,如Edit。 以下屏幕显示最后一栏没有编辑链接的数据。

enter image description here

Javascript代码:

<script language="javascript" type="text/javascript">
    function editFmatter(cellvalue, options, rowObject) {
        var cellHtml = "<a href='#' originalValue='" + cellvalue + "'>" + cellvalue + "</a>";
        return cellHtml;
    }
    function unformatEdit(cellvalue, options) {
        return $(cellObject.html()).attr("originalValue");
    }

    jQuery(document).ready(function () {
        jQuery("#list").jqGrid({
            url: '@Url.Action("JQGridGetGridData", "TabMaster")',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['col ID', 'First Name', 'Last Name', 'Edit'],
            colModel: [
                      { name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
                      { name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
                      { name: 'LastName', index: 'LastName', width: 150, align: 'left', editable: true },
                      { name: 'Edit', index: 'Edit', width: 80, align: "center", editable: true, formatter: editFmatter, unformat: unformatEdit }
                    ],
            pager: jQuery('#pager'),
            rowNum: 100,
            rowList: [10, 50, 100, 150],
            sortname: 'colID',
            sortorder: "asc",
            viewrecords: true,
            multiselect: true,
            imgpath: '@Url.Content("~/Scripts/themes/steel/images")',
            caption: 'Tab Master Information'
        }).navGrid('#pager', { edit: true, add: true, del: true },
        // Edit options
                {
                savekey: [true, 13],
                reloadAfterSubmit: true,
                jqModal: false,
                closeOnEscape: true,
                closeAfterEdit: true,
                url: '@Url.Action("JQGridEdit", "TabMaster")',
                afterSubmit: function (response, postdata) {
                    if (response.responseText == "Success") {
                        jQuery("#success").show();
                        jQuery("#success").html("Record updated successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
                        jQuery("#success").fadeOut(6000);
                        return [true, response.responseText]
                    }
                    else {
                        return [false, response.responseText]
                    }
                }
            },
        // Add options
                {
                url: '@Url.Action("JQGridCreate", "TabMaster")',
                closeAfterAdd: true,
                afterSubmit: function (response, postdata) {
                    if (response.responseText == "Success") {
                        jQuery("#success").show();
                        jQuery("#success").html("Record added successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
                        jQuery("#success").fadeOut(6000);
                        return [true, response.responseText]
                    }
                    else {
                        return [false, response.responseText]
                    }
                }
            },
        // Delete options
               {
               url: '@Url.Action("JQGridRemove", "TabMaster")',
               afterSubmit: function (response, rowid) {
                   if (rowid.length > 0) {
                       jQuery("#success").show();
                       jQuery("#success").html("Record deleted successfully! [" + rowid + "]");
                       jQuery("#success").fadeOut(6000);
                       return [true, response.responseText]
                   }
                   else {
                       return [false, response.responseText]
                   }
               }
           },
                {
                    closeOnEscape: true,
                    multipleSearch: false,
                    closeAfterSearch: true
                }
                   );
    });
</script>
@using (Html.BeginForm())
{
    <p>
        @Html.ActionLink("Create New", "Create") | @Html.ActionLink("Bulk Insert", "AddList")
        @* | @Html.ActionLink((string)ViewBag.RemoveSelectedTitle, "RemoveSelected")*@
    </p>

    <table id="list" class="scroll" cellpadding="0" cellspacing="0" width="100%">
    </table>
    <div id="pager" class="scroll" style="text-align: center;">
    </div>
    <div id="success" style="color: Green">
    </div>

Controller.cs

public JsonResult JQGridGetGridData(string sidx, string sord, int rows, int page)
        {
            int totalRecords = Convert.ToInt32(_tabmasterService.Count());
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (from tm in tabmasters
                        select new
                        {
                            id = tm.colID,
                            cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName, "Edit" }
                        }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

2 个答案:

答案 0 :(得分:0)

首先,我建议您查看thisthis个答案,了解如何在jqGrid中实现编辑链接。

您当前的代码存在一些问题:

  • unformatEdit中,您忘记定义第三个参数cellObject并使用未定义的值。
  • 添加不符合HTML标准的originalValue等属性并不好。如果确实需要扩展属性,则应在属性名称中使用data-前缀以符合HTML5。例如,您可以将代码更改为$(cellObject).children('a:first').attr("data-originalValue");
  • 由于可能的名称冲突,定义全局函数并不好。您可以在jQuery(document).ready(function () {/*here*/});事件处理程序中移动函数的声明。您可以将函数定义为变量:var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/};,然后以与以前相同的方式使用。
  • 您应该使用jqGrid的最新版本(目前为4.1.1)。您使用的许多参数(例如imgpath)多年来都不存在(请参阅here)。如果您查找更新的ASP.NET MVC代码示例,我建议您查看the answer的“更新”部分并下载相应的代码示例(VS2008 projectthe VS2010 project )。

答案 1 :(得分:0)

我已经解决了自己的问题。

我做了以下事情:

 { name: 'Edit', index: 'Edit', width: 80, align: 'center', editable: false, formatter: editFmatter, unformat: unformatEdit }

function editFmatter(el, cellval, opts) {
        var editHTML = "<img src='Images/row_edit.gif' alt='Edit' title='Edit' onclick='openEditDialog(" + opts.rowId + ");'>";
        var deleteHTML = "<img src='Images/row_delete.gif' alt='Delete' title='Delete' onclick='openDeleteDialog(" + opts.rowId + ");'>"; ;
        var finalHTML = editHTML + " " + deleteHTML;
        $(el).html(finalHTML);
    }
    function unformatEdit(cellvalue, options) {
        //return $(el).html().attr("originalValue");
    }

谢谢,
Imdadhusen