0

My .ascx page has two jqGrids

$(document).ready(function () {
    var searchText = "";

    $("#cclist").jqGrid({

        //url: ResolveUrl() + '/CC_DoctorList',
        datatype: 'local',
        // postData: { "CaseNo": CaseNo },
        mtype: 'POST',
        ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
        serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
        jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
        colNames: ['Remove', 'DoctorID', 'Last Name', 'First Name', 'Address'],
        colModel: [
            { name: 'RemoveAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
            { name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
            { name: 'LastName', index: 'LastName', width: 100, hidden: false, sortable: false },
            { name: 'FirstName', index: 'FirstName', width: 100, hidden: false, sortable: false },
            { name: 'Address', width: 420, hidden: false, sortable: false,
                jsonmap: function (obj) {
                    var street = obj.Address.Address1
                    var city = obj.Address.City
                    var state = obj.Address.StateProvince
                    var zip = obj.Address.PostalCode

                    if (street != '') { street = street + ', ' }
                    if (city != '') { city = city + ', ' }
                    if (state != '') { state = state + ', ' }

                    var Address = street + city + state + zip
                    return Address
                }
            }
        ],
        gridComplete: function () { addDeleteIcon(); },
        pager: '#ccpager',
        rowNum: 100,
        rowList: [100, 200],
        sortname: 'LastName',
        sortorder: 'desc',
        viewrecords: true,
        gridview: true,
        height: "100%",
        caption: 'Send Copy of Report To:',
        multiselect: false,
        shrinkToFit: false,
        loadui: "disabled"
    })//.jqGrid('navGrid', '#ccpager', { edit: false, add: true, del: false, search: true });

    $("#list").jqGrid({
        url: ResolveUrl() + '/DoctorList',
        datatype: 'local',
        postData: { "searchText": searchText },
        mtype: 'POST',
        ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
        serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
        jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
        colNames: ['Add', 'DoctorID', 'Last Name', 'First Name', 'Address'],
        colModel: [
    { name: 'AddAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
    { name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
    { name: 'LastName', index: 'LastName', width: 100, hidden: false, frozen: true, sortable: false },
    { name: 'FirstName', index: 'FirstName', width: 100, hidden: false, frozen: true, sortable: false },

    { name: 'Address', width: 420, hidden: false, sortable: false,
        jsonmap: function (obj) {
            var street = obj.Address.Address1
            var city = obj.Address.City
            var state = obj.Address.StateProvince
            var zip = obj.Address.PostalCode

            if (street != '') { street = street + ', ' }
            if (city != '') { city = city + ', ' }
            if (state != '') { state = state + ', ' }

            var Address = street + city + state + zip
            return Address
        }
    }],
        gridComplete: function () {
            var ids = jQuery("#list").jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                var cl = ids[i];
                var rd = $("#list").getRowData(cl);
                var imageid = 'addImg_' + rd['ID']
                be = "<div><image style='height:22px;width:20px;'  alt='' src='" + ResolveUrl('//img/icons/add_black.png') + "'></image></div>"//"<input type='button' value='Remove' onclick=\"jQuery('#rowed2').editRow('" + cl + "');\"  />";

                jQuery("#list").jqGrid('setRowData', ids[i], { AddAction: be });
            }
        },
        pager: '#pager',
        rowNum: 5,
        rowList: [5, 10, 15, 20],
        sortname: 'LastName',
        sortorder: 'desc',
        viewrecords: true,
        gridview: true,
        caption: 'Search Result',
        multiselect: false,
        height: "100%",
        shrinkToFit: false
    })

    jQuery("#list").click(function (e) {
        var el = e.target;
        if (el.nodeName !== "TD") {
            el = $(el, this.rows).closest("td");
        }
        var iCol = $(el).index();
        var row = $(el, this.rows).closest("tr.jqgrow");
        var rowId = row[0].id;
        var noMatch = 0;

        if (iCol == 0) {
            var rd = $("#list").getRowData(rowId);
            var DoctorID = rd['ID'];
            //check if the doc already exists in the cc doc list
            var ids = jQuery("#cclist").jqGrid('getDataIDs');

            if (ids.length == 0) {
                ids.length = ids.length + 1;
            }
            for (var i = 0; i < ids.length; i++) {
                var cl = ids[i];
                var ccrd = $("#cclist").getRowData(cl);

                var newrowid = ids.length + 1;

                var ccDoctorID = ccrd['ID'];


                if (DoctorID != ccDoctorID) {
                    noMatch = noMatch + 1;
                    if (noMatch == ids.length) {
                        var deleteImageIcon = "<div><image style='height:22px;width:20px;'  alt='' src='" + ResolveUrl('//img/icons/trashbin.png') + "'></image></div>"; // onclick=\"jQuery('#cclist').delRowData('" + rowId + "');\"

                        jQuery("#cclist").jqGrid('addRowData', newrowid, { RemoveAction: deleteImageIcon, ID: rd['ID'], LastName: rd['LastName'], FirstName: rd['FirstName'], Number: rd['Number'], Address: rd['Address'] });

                        // alert(ids);
                        // var hdnids = document.getElementById('hdnDocIDs').value;

                        // hdnids.value = rd['ID'];
                        //var hdnids = jQuery("#<%=hdnDocIds.ClientID %>").val();
                        //alert(hdnids);
                        //hdnids = rd['ID'];
                        //alert('hdnvalue :' + hdnids);
                        //$("#<%=hdnlbldocs.ClientID%>").val(rd['ID'].toString() + ',' + $("#<%=hdnlbldocs.ClientID%>").val())
                        //$("#<%=hdnlbldocs.ClientID%>").val(rd['ID']);
                        //alert($("#<%=hdnlbldocs.ClientID%>").val());
                        //alert($("#<%=hdnlbldocs.ClientID%>").val(rd['ID'] + ','));
                        //alert($("#<%=hdnlbldocs.ClientID%>").val());
                        //jQuery("#<%=hdnDocIDs.ClientID %>").val(rd['ID']);

                        //The below works as expected - working.
                        jQuery("#<%=hdnDocIDs.ClientID %>").val(jQuery("#<%=hdnDocIDs.ClientID%>").val() + ',' + rd['ID']);
                        alert('All hdn ids : ' + jQuery("#<%=hdnDocIDs.ClientID%>").val());
                        //Using hidden fields it concatenates the doc ids - working

                        //alert('in side the for loop ID 2:' + rd['ID'] + ' DoctorID : ' + DoctorID);
                        //var furl = ResolveUrl() + '/AddCCDoctor';
                        //var furl = '';
                        //var param = '{"CaseNo":"' + CaseNo + '", "DoctorID":"' + DoctorID + '"  }';
                        //var param = '{ "DoctorID":"' + DoctorID + '"  }';
                        //var callback = function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
                        // ajaxJsonCall(furl, param, callback);
                        //jQuery("#cclist").jqGrid('setGridParam', {datatype: 'json'}).trigger('reloadGrid');
                        function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
                    }
                }
            }

        }
    });

The #list grid gets loaded by clicking on the Search button that I have not posted in the above code. Once the #list jqGrid is loaded users can click on the rows they are interested in and those rows are added to the #cclist jqgrid.

Now, to make the .ascx more generic I need to be able to write a public method in the code behind to return all the rows IDs (doctorIDs) that are added to the #cclist jqGrid and save the IDs to the database.

Can someone help me out on how to do this?

Oleg
  • 220,925
  • 34
  • 403
  • 798
noob
  • 31
  • 1
  • 4
  • why dont you make one ajax request using Jquery on loadComplete event of your second grid, i.e #cclist. here you can get the doctorIDs of all the rows using getDataIDs, something like this var allRowsOnCurrentPage = $('#cclist').jqGrid('getDataIDs'); and the var docIds=allRowsOnCurrentPage.docIds. within a loop and send this data to server? – Piyush Sardana Aug 15 '12 at 05:47
  • Hi Piyush, Thanks for the taking time to read my posting. I am a bit new to this jqGrid. I am not sure if I have enough knowledge to understand what your are saying on jqGrid. So if I understand it right, the couple of lines of code that you posted above 'var allRowsOnCurrentPage = $('#cclist').jqGrid('getDataIDs'); 'var docIds = allRowsOnCurrentPage.docIds can be used in the vb.net code behind? I am wondering if there is a way where I can retrieve all the rows from the .ascx.vb file by writing a public method? – noob Aug 15 '12 at 17:36
  • not this would not be in ur code behind file you will have to write this in UI itself, but you can send this data to ur public method in your code behind page and from there you can save it in database. – Piyush Sardana Aug 15 '12 at 18:18
  • I'll write a demo code for u, in this i will use a button which will take the data(docIds) from ur second grid and take that data to server. I will use asp.net mvc, you can simply use vb.net, just need to change url pattern – Piyush Sardana Aug 15 '12 at 18:21

2 Answers2

0

You see this answer, here I'm getting data out of selected rows and sending that to server method. Have a save button in your page like the one in answer

Now in your case you want data from entire grid. So for you code will be like this.

$('#clickMe').click(function() {
   var rowsOnPage=[];
   var docId=[];
   rowsOnPage=$('#cclist').jqGrid('getDataIDs');
   for(var i=0;i<rowsOnPage.length;i++)
   {
   docId.push(rowsOnPage[i].ID);
   }
    $.ajax({
        type: 'POST',
        url: '@Url.Action("editMe")',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({DoctorID:docID })
        dataType: "json",
        success: function() {
            $('#grid').trigger("reloadGrid");
        },
        error: function() {
            alert("error");
        }
    }); 
});

and the server method(in ASP.NET MVC) which will be your code behind method in your approach will be like this.

//depends upon dataType of DoctorID(int or string)
public ActionResult editMe(string[] DoctorID)
{
}
Community
  • 1
  • 1
Piyush Sardana
  • 1,748
  • 4
  • 19
  • 33
  • Hi Piyush, Thanks for the sample. But I am not using MVC just the asp.net. Also, I can't use a button on the page. I think we are close based on your explanation. I sent you a linkedin invitation. Shall we connect? Mean while let me try putting the code together and see if I can make any progress on this. And also when you said url: '@Url.Action("editMe")' in your code example is it not going be the web method? But I think we are looking to define a public method in the codebehind file where I have these jqGrids? Thanks DM – noob Aug 16 '12 at 01:06
  • url: '@Url.Action("editMe")' is a normal method in controller, similar to the one in code behind. http://www.trirand.net/examples/grid/loading_data/sqldatasource/default.aspx check out this example, this is asp.net with c# this has code behind thing. Okay so they are having a button and some hidden fields in their page, inside script tag they are selecting values from selected rows(you can get all the rows here) and then putting values in hidden field. Now they have a button_click method in code behind where they are using that hidden field. This can be useful to you. – Piyush Sardana Aug 16 '12 at 02:37
  • Piyush, below lines of code doesn't return the ID values. I alwyas see it as undefined. Am I missing something? var allRowsOnCurrentPage = $('#cclist').jqGrid('getDataIDs'); var selectedRows = []; var ID = allRowsOnCurrentPage.ID; alert('ID :' + DoctorID); // I alway see undefined like ID : undefined for (var row in selectedRows) { alert('row.ID :' + row.ID); selectedValues = selectedValues + row + ","; } – noob Aug 16 '12 at 15:39
  • @noob: The line `var allRowsOnCurrentPage = $('#cclist').jqGrid('getDataIDs');` initialize `allRowsOnCurrentPage` as **array** of ids. So you can use `allRowsOnCurrentPage[0]`, `allRowsOnCurrentPage[1]`, ... `allRowsOnCurrentPage[allRowsOnCurrentPage.length-1]`. The syntax `allRowsOnCurrentPage.ID` is definitively wrond and so it returns `undefined`. – Oleg Aug 16 '12 at 17:48
  • @PiyushSardana: I think that one can use `getRowData` without parameters instead of usage of `getDataIDs` to get data from entire grid. See [the answer](http://stackoverflow.com/a/3817174/315935) as an old example of the same problem. – Oleg Aug 16 '12 at 18:28
  • @Oleg, he only wants to get doctor IDs not entire grid data, If he wants to save entire gridData then he can go for getRowData else this approach could work, isn't? – Piyush Sardana Aug 16 '12 at 18:44
  • @PiyushSardana: If one needs just all ids one can use `data: JSON.stringify({DoctorID: $('#cclist').jqGrid('getDataIDs')})`. You don't use `allRowsOnCurrentPage[i].ID`. – Oleg Aug 16 '12 at 18:54
  • okay..based on your comment i'm going to update my code again...i cant test it. I'm away – Piyush Sardana Aug 16 '12 at 19:04
  • Hello, I have put the code as below and it is working as expected. var hiddenField = $("#<%= hdnDocIDs.ClientID %>"); var selectedValues = ""; function updateSelectedRowsHidden() { var selectedRows = []; selectedRows = $('#cclist').jqGrid('getDataIDs'); selectedValues = ""; hiddenField.val(""); for (var i = 0; i < selectedRows.length; i++) { var myRow = $('#cclist').jqGrid('getRowData', selectedRows[i]); selectedValues = selectedValues + myRow.ID + ","; } hiddenField.val(selectedValues); } – noob Aug 17 '12 at 01:52
  • @Oleg, I'm sorry Sir, but this getDataIDs returns the row number not the data from Grid(doctor ID). You totally confused me> just Now i could verify this. – Piyush Sardana Aug 17 '12 at 06:22
0

Thanks for taking time to read my post and posting your comments. I put the code in a function as below and it is working as expected.

var hiddenField = $("#<%= hdnDocIDs.ClientID %>"); var selectedValues = "";

function updateSelectedRowsHidden() {

    var selectedRows = [];
    selectedRows = $('#cclist').jqGrid('getDataIDs');
    selectedValues = "";
    hiddenField.val("");

    for (var i = 0; i < selectedRows.length; i++) {
         var myRow = $('#cclist').jqGrid('getRowData', selectedRows[i]);
         selectedValues = selectedValues + myRow.ID + ",";
    }

    hiddenField.val(selectedValues);
}
noob
  • 31
  • 1
  • 4