0

I have jqGrid with enabled EDIT, DELETE, ADD and VIEW, Now my problem is when i click on edit button then it will success fully open Dialog with edit mode. now when i am submitting my changes then it will pass jqGrid Row Index instead of ColID (ColId is PK with AutoIdentity True). I would like to pass ColID as parameter.

following is my code snippet:

jQuery(document).ready(function () {
    jQuery("#list").jqGrid({
        //url: '/TabMaster/GetGridData',
        url: '/TabMaster/DynamicGridData',
        datatype: 'json',
        mtype: 'GET',
        colNames: ['col ID', 'First Name', 'Last Name'],
        colModel: [
            { name: 'colID', index: 'colID', width: 100, align: 'left' },
            { name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
            { name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true }
        ],
        pager: jQuery('#pager'),
        rowNum: 4,
        rowList: [1, 2, 4, 5, 10],
        sortname: 'colID',
        sortorder: "asc",
        viewrecords: true,
        gridview: true,
        multiselect: true,
        imgpath: '/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: "/TabMaster/Edit/",
        afterSubmit: function (response, postdata) {
            if (response.responseText == "Success") {
                jQuery("#success").show();
                jQuery("#success").html("Company successfully updated");
                jQuery("#success").fadeOut(6000);
                return [true, response.responseText]
            }
            else {
                return [false, response.responseText]
            }
        }
    });
});

here is i am getting JQRowIndex

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection updateExisting)
{
    TabMasterViewModel editExisting = new TabMasterViewModel();
    editExisting = _tabmasterService.GetSingle(x => x.colID == id);
    try
    {
        UpdateModel(editExisting);
        _tabmasterService.Update(editExisting);
        return Content("Success");
    }
    catch
    {
        return Content("Failure Message");
    }
}

Here is the logic to generate JSON response. Method:1 *This is not display any record, even also dosen't fire any exception*

 public JsonResult DynamicGridData(string OrderByColumn, string OrderType, int page, int pageSize)
    {
        int pageIndex = Convert.ToInt32(page) - 1;
        int totalRecords = GetTotalCount();
        int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
        IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(OrderByColumn, OrderType, page, pageSize);
        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 }
                    }).ToArray()
        };
        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

The following is working perfectly. (this is working fine but i want to use Method:1 instead of Method:2) Method:2

public ActionResult GetGridData(string sidx, string sord, int page, int rows)
        {
            return Content(JsonForJqgrid(GetDataTable(sidx, sord, page, rows), rows, GetTotalCount(), page), "application/json");
        }
        public int GetTotalCount()
        {
            return Convert.ToInt32(_tabmasterService.Count());
        }
        public DataTable GetDataTable(string OrderByColumn, string OrderType, int page, int pageSize)
        {
            TabMasterListViewModel models = _tabmasterService.GetTabMasterList(OrderByColumn, OrderType, pageSize, page);
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("colID", Type.GetType("System.Int32")));
            dt.Columns.Add(new DataColumn("FirstName", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("LastName", Type.GetType("System.String")));
            foreach (TabMasterViewModel model in models.TabMasterList)
            {
                DataRow dr = dt.NewRow();
                dr[0] = model.colID;
                dr[1] = model.FirstName;
                dr[2] = model.LastName;
                dt.Rows.Add(dr);
            }
            var rows = dt.Rows.Count;
            return dt;
        }
        public static string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords, int page)
        {
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{");
            jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
            jsonBuilder.Append(":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{\"id\":" + dt.Rows[i][0].ToString() + ",\"cell\":[");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }
imdadhusen
  • 2,493
  • 7
  • 40
  • 75

1 Answers1

2

I suppose that the origin of your problem is wrong filling of JSON data in the GetGridData. Because your code contain imgpath I could suppose that you use some very old example of jqGrid. In some old examples it was a bug that one used i instead of id in the JSON data. If jqGrid don't find id property in the input data it uses integers 1, 2 and so on as ids. I suppose it is your case. If you includes at least the last lines of your GetGridData we would see that.

I recommend you to look at the UPDATED part of the answer and download the corresponding demo project. It shows not only how to implement data paging, sorting and filtering in ASP.NET MVC 2.0 but shows additionally how to use exceptions to return informations about an error from the ASP.NET MVC.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Thanks for your valuable comments, Let me check it and then let you know! – imdadhusen Jun 13 '11 at 08:45
  • as per your suggestion i have replaced i with id and now it is working as per expected. now i modified my logic for JSON then it will not work – imdadhusen Jun 13 '11 at 09:38
  • @imdadhusen: I don't recommend you to make JSON serialization manually like you do this in `JsonForJqgrid`. You should use [JavaScriptSerializer](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=VS.90).aspx) instead. Moreover in case of errors you should returns some error (>400) HTTP error code. To format the error message after editing you can use `errorTextFormat` in the JavaScript code. The code `return Json(jsonData);` in the "Method 1" will work only in MVC 1.0. It should be `return Json(jsonData, JsonRequestBehavior.AllowGet));` in MVC 2.0. – Oleg Jun 13 '11 at 09:55
  • @imdadhusen: Additionally the usage of `DataTable` inside of `GetDataTable`. The `List>` can be good used instead. – Oleg Jun 13 '11 at 10:00
  • thanks for your quick reply. could you help me to write function for return JSON in MVC 3.0 using Method:1? – imdadhusen Jun 13 '11 at 10:02
  • i am very new MVC, Thus i don't have much idea about good or bad so pleas guide me if it would be possible for you. – imdadhusen Jun 13 '11 at 10:04
  • @imdadhusen: just use `return Json(jsonData, JsonRequestBehavior.AllowGet));` as the last line of `DynamicGridData`. [The example](http://www.ok-soft-gmbh.com/jqGrid/jqGridDemo.zip) from [the answer](http://stackoverflow.com/questions/5500805/asp-net-mvc-2-0-implementation-of-searching-in-jqgrid/5501644#5501644) which I mentioned in my answer could be good starting point. It could be easy used in ASP.NET MVC 3. – Oleg Jun 13 '11 at 10:14
  • @imdadhusen: In the updated code which you posted there are still `Json(jsonData)` and not `Json(jsonData, JsonRequestBehavior.AllowGet))`. You old code with `Json(jsonData)` will works only if you would use `mtype: 'POST'` instead of `mtype: 'GET'`. I don't understand which code you use at the end and which is not work. – Oleg Jun 13 '11 at 10:45
  • sorry for confusion! i have updated code on my machine not here. now i updated DynamicGridData here and modified return type is JsonResult also. Please help me. – imdadhusen Jun 13 '11 at 11:33
  • 1
    @imdadhusen: First of all you should change the `string OrderByColumn, string OrderType, int page, int pageSize` parameter names to `string sidx, string sord, int page, int rows` and correct the corresponding body of your `DynamicGridData` method. Then you can set breakpoint inside of the method to verify that the method will be called. then you can use [Fiddler](http://www.fiddler2.com/fiddler2/) to capture the JSON data posted back to the jqGrid. You can include the JSON data in the question. – Oleg Jun 13 '11 at 11:49
  • Now finally it working....**Thank you very much Oleg** could please let me know why should i have to pass paramters in this order with exact name (string sidx, string sord, int page, int rows)? again thanks for your support. my vote is + – imdadhusen Jun 13 '11 at 13:29
  • @imdadhusen: You are welcome! The order of parameters are not important, but the names are important. If you want use another names on the server side you have to rename the parameters which use jqGrid with respect of [prmNames](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options) option. – Oleg Jun 13 '11 at 13:33
  • Can i ask one more question? because i am stuck since a day! – imdadhusen Jun 13 '11 at 13:45
  • **I am note able to DELETE and ADD records as well?** so please could you guide me for the same? seeking for your co-operation. – imdadhusen Jun 13 '11 at 13:58
  • @imdadhusen: You can include `string oper` in your `Edit` action. See `ModifyData` method [here](http://stackoverflow.com/questions/3917102/jqgrid-add-row-and-send-data-to-webservice-for-insert/3918615#3918615) (the `string exercise_value` is not needed in your case). – Oleg Jun 13 '11 at 14:12