如何在jqgrid中删除时显示错误消息?

时间:2013-12-08 17:31:31

标签: c# jquery jqgrid

对所有人来说,我正在使用jqgrid,并且想要显示错误消息,如果用户想要删除正在使用的卡车记录,我必须显示正在使用的卡车错误消息。 这是我的jqgrid: -

    jQuery(document).ready(function () {


        var grid = jQuery("#TrucksGrid141");

        grid.jqGrid({
            url: '/Admin/GetTrucksForJQGrid',
            datatype: 'json',
                mtype: 'Post',
                 cellsubmit: 'remote',
               cellurl: '/Admin/SaveTruck',
               height: '100%',
               pager: '#pagerTrucks',

            colNames: ['Id', 'Name', ''],
            colModel: [
            { name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
            { name: 'Name', index: 'Name', align: "center", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },


            { name: 'Delete', index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }

            ],    



            width: '490',           
            caption: 'Company Trucks',
            hidegrid: false,
            delete: true,
            cellEdit: true,
            viewrecords: true,
            gridComplete: function () {

                var ids = grid.jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
                    if (isDeleted != 'true') {
                        grid.jqGrid('setCell', ids[i], 'Delete', '<a href="#" onclick="deleteRow(' + ids[i] + ');"><img src="/Images/delete.png" alt="Delete Row" /></a>');
                    }
                    else {
                        grid.jqGrid('setCell', ids[i], 'Delete', ' ');
                        //grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
                    }
                }
            }
        }

        );

        grid.jqGrid('navGrid', '#pagerTrucks',
       { resize: false, add: false,search:false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }

   ).jqGrid('navButtonAdd', '#pagerTrucks',
       { title: "Add New Truck", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewTruckModal, position: "First", caption: "" });

    });

    function showNewTruckModal() {

        var grid = jQuery("#TrucksGrid141");
        $("#formAddNewTruck").dialog(
                {
                    open: function (event, ui) {

                        $("#txtName").val('');
                        $("#trFormErrorTrucks").hide();
                        $("#trFormErrorTrucks td").text('');

                    },
                    buttons: {
                        "Submit": function () {
                            debugger;
                            if (ValidateUsers() == true) {
                                $('#error').ajaxError(function (event, request, settings) {
                                    $('#waiting').hide();
                                    $(this).addClass('errordiv').text(request.statusText + "" + request.status);

                                });
                                $.post('/Admin/AddNewTruck/',
                                $('#formAddNewTruck').serialize(),
                                function (data) {
                                    debugger;
                                    if (data == 'Success') {
                                        $('#formAddNewTruck').dialog("close");
                                        grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
                                    }
                                    else {
                                        $("#trFormErrorTrucks").show();
                                        $("#trFormErrorTrucks td").text(data);
                                    }

                                });
                            }
                        },
                        "Cancel": function () {
                            $('#error').removeClass("errordiv").text("");
                            $('#waiting').hide();
                            $(this).dialog("close");
                        }
                    },
                    modal: true,
                    title: "New Truck",
                    minWidth: 400,
                    resizable: false
                }
        ).dialog('open');
    }

    function ValidateUsers() {
            var flag = true;
            var errorMSG = '';
            $("#trFormErrorTrucks td").text('');
            if ($("#txtName").val() == '') {
                errorMSG += 'Truck Name cannot be blank';
                flag = false;
            }


            if (flag == false) {
                $("#trFormErrorTrucks").show();
                $("#trFormErrorTrucks td").text(errorMSG);
            }
            else {
                $("#trFormErrorTrucks td").text('');
                $("#trFormErrorTrucks").hide();
            }
            return flag;
        }

    function deleteRow(rowid) {
        jQuery("#TrucksGrid141").delGridRow(rowid, { url: '/Admin/TruckDelete', caption: 'Delete User?', msg: 'Delete selected User? <br />Careful, this is irreversable!', resize: false,success:abc });
        }

        function emptyText(rowid, cellname, value, iRow, iCol) {
            if (cellname == 'Password')
                return "";
        }
        function abc(data)
        {
            debugger;
        }


    and here is my cs code from controller:

  [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TruckDelete(int Id)
        {
            var error = "";
            bool result=true;
            DataContext db = new DataContext();
           Truck udelete= db.Trucks.Where(el => el.Id == Id).FirstOrDefault();
           if (udelete != null)
           {
               JobSites_ForSnow snow = db.JobSites_ForSnow.Where(el => el.TruckId == Id).FirstOrDefault();
               JobSite normal = db.JobSites.Where(el => el.TruckId == Id).FirstOrDefault();
               if(snow==null && normal==null)
               {
               db.Trucks.Remove(udelete);           
               db.SaveChanges();
               }
               else
               {
                error = "Truck in use!";
               result= false;
               }
           }
           else 
           {
               error = "Record Not Found!";
               result= false;
           }
            return Json(result,error);
        }

任何人都可以告诉我如何显示错误信息?我已经看到了这个答案(jqgrid error message on delete),但不明白该怎么做:(。如果问题不清楚,请通过评论告诉我,我会解释......先谢谢:)

1 个答案:

答案 0 :(得分:3)

您目前使用

return Json(result,error);

作为TruckDelete操作的最后一行,其中result具有布尔类型,error是字符串。因此,Controller.Json Method (Object, String) error将被解释为HTTP响应的contentType。这是你的第一个问题。你应该使用像

这样的东西
return Json(new Object[] {result, error});

(见here)。在这种情况下,该方法将生成像

这样的JSON响应
[true,""]

[false,"Record Not Found!"]

客户端(jqGrid)可以处理afterSubmit回调内的响应。您只需将success的未知(对于jqGrid)选项delGridRow替换为以下

jQuery("#TrucksGrid141").delGridRow(rowid, {
    url: '/Admin/TruckDelete',
    caption: 'Delete User?',
    msg: 'Delete selected User? <br />Careful, this is irreversable!',
    resize: false,
    afterSubmit: function (jqXHR) {
        return $.parseJSON(jqXHR.responseText); // return decoded response
    }
});