Custom template column does not work in JQGrid

2019-09-03 06:00发布

问题:

Experts,

I have JQGrid with custom template column like Edit. the following screen display data without Edit link in last column.

Javascript code:

<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);
        }

回答1:

First of all I would recommend you to take a look in this and this answers which shows how you can implement Edit links in the jqGrid.

Your current code have some problems:

  • In the unformatEdit you forgot to define the third parameter cellObject and use undefined value.
  • It's not good to add attributes like originalValue which are not corresponds to HTML standards. If you do need to extend attributes you should use data- prefix in the attribute name to be HTML5 compliant. In the case you can change the code to $(cellObject).children('a:first').attr("data-originalValue"); for example.
  • It is not good to define global functions because of possible name conflicts. You can move declaration of the function inside of jQuery(document).ready(function () {/*here*/}); event handler. You can define the function like a variables: var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/}; and use later in the same way like you did as before.
  • You should use the last version of jqGrid (currently 4.1.1). Many parameters like imgpath which you use are not exist since years (see here). If you look for more recent ASP.NET MVC code example I would recommend you take a look in the "UPDATED" part of the answer and download the corresponding code examples (the VS2008 project and the VS2010 project).


回答2:

I have solved question from myself.

I have done following:

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

and

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

Thanks,
Imdadhusen