0

I've been trawling across the web for answers, and maybe it's a case of it being more complicated than I expect (or I just don't understand the solutions), but I am looking for a way to simply delete a selected row from my jqgrid by clicking the trash icon.

Currently my grid is being populated with Linq to SQL data. Here is my grid:

jQuery("#grid").jqGrid({
                     url: '<%= ResolveUrl("~/Home/GetData") %>',
                     datatype: "json",
                     mtype: 'GET',
                     postData: { DDLid: function () { return jQuery("#DDL option:selected").val(); } },
                     colNames: ['Col1', 'Col2'],
                     colModel: [
                        { name: 'Col1', index: 'Col1', width: 200, editable: false },
                        { name: 'Col2', index: 'Col2', width: 200, editable: false }
                        ],
                     jsonReader: {
                         repeatitems: false
                     },
                     rowNum: 10,
                     pager: jQuery('#gridpager'),
                     sortname: 'Type',
                     viewrecords: true,
                     sortorder: "asc",
                     caption: "Table"
                 }).navGrid('#gridpager', { del: true, add: false, edit: false, search: false }, {}, {}, {url: "Delete"});

Now the 'id' in post data is NOT the primary key in this table - I just need it to help populate the grid. What I would like to get is the selected row id and pass it to the Delete method, but I can't find any way to do that.

I have tried using jQuery("#grid").getGridParam('selrow') in the postData but it always returns null.

Any help would be greatly appreciated.

Here is my delete method, for reference:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Delete(int DDLid) 
    {
        int row = Convert.ToInt32(/*I NEED THIS ID*/);
        var query = from x in _ctx.DataTable
                    where ((x.id == row))
                    select x;
        _ctx.DataTable.DeleteOnSubmit(query.Single());
        _ctx.SubmitChanges();
        return Json(true);
    }

This method is called and is fine, but I am getting the wrong id. I need the selected row's id. This breaks because the DDLid returns more than one row (since it is used to populate the grid).

I hope that makes sense.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • should not the mtype be POST/DELETE rather than GET? – Sunny May 14 '12 at 22:24
  • I had the navGrid like so, and the same result occured: `.navGrid('#gridpager', { del: true, add: false, edit: false, search: false }, {}, {}, { url: "Delete", mtype: "POST", reloadAfterSubmit: true });` – QuestionableSounder May 14 '12 at 22:29

3 Answers3

1

I discovered where I would pass the selected index (but then I realised I was looking for the primary key, rather than selected index, but it is the same result regardless)

I needed to add this to my navGrid:

 {url: "Delete", mtype: "POST", reloadAfterSubmit: true, 
       serializeDelData: function (postdata) {
                         var selectedrowindex = jQuery("#grid").jqGrid('getGridParam', 'selrow');
                         var dataFromCellByColumnIndex = jQuery('#grid').jqGrid ('getCell', selectedrowindex , 1); 
                         return {DDLid: postdata.id, name: dataFromCellByColumnIndex};
       }
 });

So this passes a column value to my delete method as well as the DDLid, but I could easily swap dataFromCellByColumnIndex with selectedrowindex.

  • I wrote you before that the origin of your problem in wrong filling of ids of the data in the grid. If you append your question with the data (it would be enough to have one row of data) which will be returned from `url: '<%= ResolveUrl("~/Home/GetData") %>'` I would show you the error. The data returned by the server should contain `id`. I suppose that you don't do this. If the `'Col2'` column contains the id (primary key) you can solve the problem adding `key: true` to the column. In the case `selectedrowindex` will be the same as `dataFromCellByColumnIndex`. – Oleg May 15 '12 at 20:51
  • Yea, after looking over it some more I realised that I was being a noob and not passing in the primary key. But I did not know about the `key:true` part, so thank you! Is there any good tutorials on jqgrid that covers things like this? Because I have been having trouble finding them... – QuestionableSounder May 16 '12 at 20:42
0

You should just implement Delete action having id parameter:

public JsonResult Delete(string id) {
    ...
}

To reference the action in the JavaScript code I would use 'url: <%= Url.Action("Delete") %>' instead of url: "Delete" which you use currently.

You can download here demo project which I created for the answer. The project implement deleting of the row together with many other features which you currently not need.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • The id parameter in my code is NOT the parameter I need to delete the row (it is the id of a dropdownlist). I have already implemented a delete action like this, and it works fine (as I have used a working one before) - my only problem is that I am unable to pass in the primary key of the selected row. – QuestionableSounder May 14 '12 at 22:32
  • I have edited my answer to include the delete method too, if that helps :) – QuestionableSounder May 14 '12 at 23:59
  • @vegetas_angel: You should use `id` as the name in the `Delete` action. **It's important which name you choose for the formal parameter**. The `id` will be initialized to the value which you need: to row id. The value will be initialized to the value `$("#grid").jqGrid('getGridParam', 'selrow')`. If the value of `id` will be not what you want then would mean only that you *fill* the grid in the wrong way: the JSON data returned from `'<%= ResolveUrl("~/Home/GetData") %>'` has no `id` or on the wrong place. – Oleg May 15 '12 at 05:09
  • Ah, ok. So `id` in the Delete method can be different from the postdata one? Awesome! Thank you!! I shall do that next time :) – QuestionableSounder May 15 '12 at 20:32
  • @vegetas_angel: The `"id"` is just default name of parameter. If you want have another name you can use `prmNames` parameter of jqGrid. For example `prmNames: {id: "DDLid", oper: null}` will send row id under the name `DDLid` and will don't send `oper` parameter. – Oleg May 15 '12 at 20:55
0

You can make another post inside delete method with your own params. After defining grid, you can define each action in detail. It is posting actual delete with correctid and original one is posting fake id. JQgrid is using row count for delete not the primary key. They may change it with recent versions, but this was working Jqgrid 3.8

 jQuery("#ClientGrid").jqGrid('navGrid', '#ClientGridPager',
{ view: true, edit: true, search: false }, //options
{height: 240, caption: 'Edit Client', beforeShowForm: hideIDColumn, reloadAfterSubmit: true, mtype: 'POST', url: "/Settings/EditClient", jqModal: false, closeOnEscape: true, bottominfo: "Fields marked with (*) are required" }, // edit options
{height: 340, caption: 'Add Client', beforeShowForm: hideIDColumn, reloadAfterSubmit: true, mtype: 'POST', url: "/Settings/CreateClient", jqModal: false, closeOnEscape: true, bottominfo: "Fields marked with (*) are required", closeAfterAdd: true }, // add options
//delete method
{reloadAfterSubmit: true, beforeSubmit: function (postdata, formid)
{
    var lastselectedID = -1;
    if (ClientGridrow != null || typeof (ClientGridrow) != "undefined")
    {
        lastselectedID = $("#ClientGrid").getCell(ClientGridrow, 'ID_PK');
    }
    //CUSTOME delete to send taskid instead of rowid
    $.ajax({ type: "POST", url: "/Settings/DeleteClient/?objid=" + lastselectedID,
        data: "", success: function (response)
        {
            $("#ClientGrid").trigger("reloadGrid"); //reloadAfterSubmit: true is not working in Chrome
        }
    });
    return [true, "Delete failed message"];

}, caption: 'Delete Client', datatype: 'local', url: "/Settings/DeleteClient/?objid=-1", jqModal: false, closeOnEscape: true
}, // del options..we make two posts
  {closeOnEscape: true }, // search options
  {height: 230, width: 350, jqModal: false, closeOnEscape: true} // view options
   );
Omer Cansizoglu
  • 1,271
  • 9
  • 14