2

My jqGrid is not populating on-submitting my form in Asp.net MVC 4 ... I am want to find out why... I have an ajax method that returns this Json string and it is a Json string in the Network response browser...

"{\"total\":1,\"page\":1,\"records\":1,\"rows\":[{\"cell\":[\"\",\"342352857634\",\"test\",\"test\",\"5/8/2012 11:39:38 AM\",\"1\",\"\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\"]}]}"

this is the function that does all of the Magic.

$('#SearchPatID').submit(function (event) {
        //alert("What the motherFuck is going on here!");
        debugger;
        var theURL = this.action;
        var type = this.methd;
        event.preventDefault();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            dataType: "json",
            success: function (result) {
                debugger;
                bindData(result);
            }
        });
        return false;
    });
    var bindData = function (result) {
    debugger;
    alert('Glad this is kind-of working!');
    $("#list").setGridParam({
        datatype: 'jsonstring',
        datastr: result,
        caption: 'Suck It!'
    }).trigger("reloadGrid");
    }

UPDATE... I chamged my bindData function to Just setGridParam. and reload... Still doesn't work, but I think I am on the right path finally... More updates below...

What Am I missing? I have my Json data, everything should be working out fine right?

UPDATE:
I realized I was sending in a JSON string and not necesarrily a JSON object... so I changed the datatype to jsonstring from json... still doesn't work.

Here is what returns my JSON data. UPDATED TO WHAT I AM NOW TRYING: I wanted to try putting the column names in the data... For some reason I thought that might help

public static object JsonHelper(TemplateModel model){

        var values = model.Template;
        var JsonDataList = new {
            total = 1,
            page = 1,
            records = model.Template.Count,
            rows = (from val in values
                    select new {
                        cell = //new string(
                            "[\"id\" :\"" + val.EncounterId +",\""+
                            //"\"MRN\" :" + 
                            "\"MRN\" :\"" + val.MRN + ",\"" +
                            //"\"Hospital_Fin\" :" + 
                            "\"Hospital_Fin\" :\"" + val.HostpitalFinNumber + ",\"" +
                            //"\"First_Name\" :"+ 
                            "\"First_Name\" :\"" + val.FirstName + ",\"" +
                            //"\"Last_Name\" :" + 
                            "\"Last_Name\" :\"" + val.LastName + ",\"" +
                            //"\"Date_of_birth\" :" + 
                            "\"Date_of_birth\" :\"" + val.DateOfBirth.ToString() + ",\"" +
                            //"\"Completed_Pathway\" :" + 
                            "\"Completed_Pathway\" :\"" + val.CompletedPathway + ",\"" +
                            //"\"Completed_Pathway_Reason\" :" + 
                            "\"Completed_Pathway_Reason\" :\"" + val.CompletedPathwayReason + ",\"" +
                            //"\"PCP_Appointment\" :" + 
                            "\"PCP_Appointment\" :\"" + val.PCPAppointmentDateTime.ToString() + ",\"" +
                            //"\"Specialist_Appointment\" :" + 
                            "\"Specialist_Appointment\" :\"" + val.SpecialistAppointmentDateTime.ToString() + ",\"" +
                            //"\"Admit_Date\" :" + 
                            "\"Admit_Date\" :\"" + val.AdminDate.ToString() + "\"]"                            
                    })//.ToArray()
        };
        return JsonDataList;
    }

plus...

return Json(DataRepository.JsonHelper(model.FirstOrDefault()), JsonRequestBehavior.AllowGet);

This is how I set up my jqGrid...

$(document).ready(function () {
        $("#list").jqGrid({
                        shrinkToFit: false,
                        autowidth: true,
                        datatype: 'local',
                        mtype: 'POST',
                        colNames: ['Edit',
                                   'MRN',
                                   'Hospital Fin',
                                   'First Name',
                                   'Last Name',
                                   'Date of birth',
                                   'Completed Pathway',
                                   'Completed Pathway Reason',
                                   'PCP Appointment',
                                   'Specialist Appointment',
                                   'Admit Date'
                                   ],
                        colModel: [
                                   { name: 'Edit', width: 95, align: 'left' },
                                   { name: 'MRN', width: 125, align: 'left' },
                                   { name: 'Hospital_Fin', width: 145, align: 'left' },
                                   { name: 'First_Name', width: 115, align: 'left' },
                                   { name: 'Last_Name', width: 115, align: 'left' },
                                   { name: 'Date_of_birth', width: 145, align: 'left' },
                                   { name: 'Completed_Pathway', width: 125, align: 'left' },
                                   { name: 'Completed_Pathway_Reason', width: 165, align: 'left' },
                                   { name: 'PCP_Appointment', width: 115, align: 'left' },
                                   { name: 'Specialist_Appointment', width: 125, align: 'left' },
                                   { name: 'Admit_Date', width: 185, align: 'left' }],
                        rowNum: 10,
                        rowList: [5, 10, 20, 50],
                        sortname: 'Id',
                        sortorder: "desc",
                        viewrecords: true,
                        imgpath: '/Content/themes/UPMC-theme/images',
                        caption: 'My first grid'
    }); })

I read somewhere online that setting the datatype to 'local' and then doing the setGridParam and trigger('reload') will help somehow or the other. Seems logical. But I am still a little unsure of how that would work... Still not working yet, but I am giving it the old college try...

UDPATE: Further explanation My JsonHelper just tries to write out a valid JsonString... Does anybody have an example of how they do this regularly? Whenever I just use the standard Json ActionHelper thing... I guess I could make a different object return value, but that means I will have to mess around with more linq... And that is an adventure for another day.

**UPDATE2: Months have goneby" Hello there. I have been distracted by another project for about a month. Now that it is starting to wind down, This code is starting to vex me once again. I feel like I am so close, but yet so far...

Anyway, Here is an example of the empty jqGrid that I was talking about... example empty jqGrid
As you can see, I have two rows of data, but neither one of them, has any of the data that they normally should...

Here is what the data looks like in debug mode...

["id" :"2005,""MRN" :"840108105,""Hospital_Fin" :"999999999999985,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"6/12/2012 12:00:00 AM,""Specialist_Appointment" :"6/12/2012 12:00:00 AM,""Admit_Date" :"7/5/2012 12:00:00 AM"]
["id" :"2025,""MRN" :"840108105,""Hospital_Fin" :"789654123000123,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"1/1/0001 12:00:00 AM,""Specialist_Appointment" :"1/1/0001 12:00:00 AM,""Admit_Date" :"7/6/2012 12:00:00 AM"]

That comes right out of my JSON helper... Which basically creates two string objects out of the Models that I get back... This is what the JSON Data looks like on the client side right during the bind...

{"total":1,"page":1,"records":2,"rows":[{"cell":"[\"id\" :\"2005,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"999999999999985,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Specialist_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Admit_Date\" :\"7/5/2012 12:00:00 AM\"]"},{"cell":"[\"id\" :\"2025,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"789654123000123,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Specialist_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Admit_Date\" :\"7/6/2012 12:00:00 AM\"]"}]}

Just looking at my data, it seems kind of messed up. I am going to try and see if fixing it will make it look better. But if you have any other advice, I would definitely appreciate it.

SoftwareSavant
  • 9,467
  • 27
  • 121
  • 195
  • You should post some code fragments of the MVC action which returns the JSON response. – Oleg Jun 08 '12 at 22:15

2 Answers2

1

I suppose that you have serious problems in the server code which you use. If you make $.ajax request with parameter dataType: "json" then $.ajax convert the data to the object. The response from the server seems as though you convert the returned object to JSON twice.

I suppose that you converted the object with total, page, records and rows properties first manually to JSON using JavaScriptSerializer or DataContractJsonSerializer and then returned the results string with return Json(myJsonString);. As the result the JSON string will be additionally encoded.

Moreover if you want use the data as datastr: result you have to use datatype: 'jsonstring' instead of datatype: 'json' which requires url parameter.

To tell the trust your code have other problems. $("#list").jqGrid({...}); create the grid from <table id="list"></table> element and the code can be executed only once. You current code is written so that the function bindData can be called multiple times on every form submit.

Additionally you use gridview: false which reduce the performance (you should always use gridview: true). The option imgpath not exist in jGrid since years. I suppose that you get some very very old example of jqGrid usage and tried to modify it to your purpose.

I would recommend you to get some more recent example, like from the answer or this one as the starting point. You should better use datatype: 'json' directly and send additional parameters to the server for example like it's described here or use $.serializeArray for example (see here).

UPDATED: There are NO JSON object. Either you have just an Object or you have a string which could represent an Object encoded corresponds to JSON standard.

You don't need to use any JsonHelper. The MVC action should just return Json(theObject) like

return new {
        total = 1,
        page = 1,
        records = model.Template.Count,
        rows = ...

};

Moreover the default format of JSON data for jqGrid described here. The code which you posted in JsonHelper contains

rows = (from val in values
        select new {
            invdata = new string[]{ ...}
        }).ToArray()

and generate rows as array of objects without id property and with invdata property instead of cell. To read the data you need at least include jsonReader: {cell: "invdata"}. The better would be to return correct data having id. If some from the column tables could be interpreted as unique id of the row you can include key: true in the corresponding column, use jsonReader: {cell: ""} and fill rows as List<List<string>> or as array which elements as array or strings.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • I kind of want the submit button in that form to kind of refresh the data in the table. Are you saying that data can only be loaded once using the jsonstring as the datatype? – SoftwareSavant Jun 09 '12 at 01:52
  • @DmainEvent: I want to say that the best would be the usage of `datatype: "json"` and to allow jqGrid the get the date from the server. To make explicit refresh of the data you need just call `$("#list").trigger("reloadGrid")`. If you use local datatype (inclusive `datatype: "jsonstring"`) you can reset the `data` parameter with respect of `setGridParam` and reload the grid. Sometimes you need additionally call `refreshIndex` (`$("#list")[0].refreshIndex()`) before trigger "reloadGrid". – Oleg Jun 09 '12 at 21:50
  • @DmainEvent: See additionally UPDATED part of my answer. – Oleg Jun 09 '12 at 22:09
  • I use the datarepository to kind of set get the string into what is needed. Also, I will update my code with what I have now. – SoftwareSavant Jun 11 '12 at 12:52
  • @DmainEvent: It's not important whether you use Entity Framework or some Repository. You should just use `jsonReader` which corresponds the data which you post. If you want use standard `jsonReader` then the item in `rows` have to have `id` and `cell` property and not `invdata` which you use. – Oleg Jun 11 '12 at 13:04
0

I think you are missing eval.

  success: function (result) {
            debugger;
            var data = eval("(" + result.d + ")");
            bindData(data);
        }
Mehmet
  • 1,824
  • 3
  • 19
  • 28