Solved

jqgrid implementation

Posted on 2011-09-14
10
2,093 Views
Last Modified: 2012-05-12
I was trying to use jqgrid using asp. I prepared the front end - html format to display data from backend server - SQL SERVER 2005 db.

I do have json format rather than xml.

I do not have a sample page to fetch the data from the server such as paging, sorting, ordering and so on. The data  source would be change dynamically via web page - not hard coded.

Therefore, would you please give a sample code to create such file as a backend?

Here is the front end file
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="demogrid.aspx.cs" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title></title>
    <!-- The jQuery UI theme that will be used by the grid -->
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/themes/redmond/jquery-ui.css" />
    <!-- The jQuery UI theme extension jqGrid needs -->
    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
    <!-- jQuery runtime minified -->
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
    <!-- The localization file we need, English in this case -->
    <script src="js/trirand/i18n/grid.locale-en.js"type="text/javascript"></script>
    <!-- The jqGrid client-side javascript -->
    <script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        jQuery.extend(jQuery.jgrid.defaults, { altRows: true });
        //jQuery("#list").setCell(row, col, val, { background: '#ff0000' });
    </script>
   
    <style>
        body { font-size: 75%; }
    </style>
</head>


<body>
    <form id="form1" runat="server">
    
   
    
 
   <script type="text/javascript">
       /*global $ */ 
       /*jslint devel: true, browser: true */ 
       $(document).ready(function () {
           $.ajax({
                            type: 'POST',
                            contentType: "application/json; charset=utf-8",
                            url: "??????.aspx",//I need the server side file here
                            datatype: 'json',
                            success: function (result) {
                               
//                                colD = result.colData;
//                                colN = result.colNames;
                                var colM = result.colModel;
                                 //alert(result.colModel);
                                jQuery("#UsersGrid").jqGrid
                                      (
                                        {
                                            //jsonReader: { repeatitems: false, cell: "", id: "0" },
                                            url: "demogrid.aspx", 
                                            datatype: 'json',
                                            mtype: 'POST',
                                            colModel: colM,
                                            
                                            //data: colD.rootVar,
                                           // ColNames: colN,
                                           // ColModel: ColM,
                                            height: "auto",
                                            gridview: true,
                                            Pager: '#Pager',
                                            rowNum: 5,
                                            rowList: [5, 10, 20, 50],
                                            viewrecords: true,
                                            loadComplete: function (data) {
                                                alert('loaded completely'); 
                                             },
                                            loadError: function () {
                                                alert('error'); 
                                             }
                                        });
                            },
                            error: function (x, e) {
                                alert(x.readyState + ' ' + x.status + e.msg);
                            }
                        });

       });
</script>
    
   
    <br /><br />
    
    <br /><br />        
    </form>
</body>
</html>

Open in new window

0
Comment
Question by:Efremdawit
  • 4
  • 3
10 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 36542655
0
 

Author Comment

by:Efremdawit
ID: 36555561
Thank you for your resourceful sites. However, I would like to have pure asp.net page rather than web service.

The URL should be aspx rather than web service. The data format from server to client could be xml or json.

The main purpose is put data (column and row) dynamically which would be the query is dynamic.

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 500 total points
ID: 36556084
>I would like to have pure asp.net page rather than web service.

>The data format from server to client could be xml or json.

a pure asp.net page is not xml or json data. you need a webservice.
additionally I see webservice in your question tags...

>The main purpose is put data (column and row) dynamically which would be the query is dynamic.
this is a webservice task
0
 

Author Comment

by:Efremdawit
ID: 36556823
ok. I will try to implement based upon linked resources.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:Efremdawit
ID: 36562885
I tried to implement the jqgrid with asp.net framework. However, I could not get the data displayed. Of course, the data is hard code for demo purpose. I will change later the data source to get the data dynamically. Now I want to solve this problem first.
Here are the two files

Later, I will change the colModel and colNames along with the data source for dynamic display for any query or table. So would you please tell me where I can put such features in the files?


GetData.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Script.Serialization"%>
<%@ Import Namespace="System.Collections.ObjectModel"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
     
        Response.Write(GetData());
        Response.End();
        //Response.Write ("Data is being loaded");
    }
    
    protected string GetData()
    {
        //if (Equals(Request.Params.Get("oper"), Oper.edit.ToString()))
        //{
        //    list = new Collection<People>
        //               {
        //                   new People {id = 1, name = Request.Params.Get("name") , gender = Convert.ToInt32(Request.Params.Get("gender")), isClosed = Convert.ToBoolean(Request.Params.Get("isClosed"))},
        //                   new People {id = 2, name = "Monu", gender = 2, isClosed = false},
        //                   new People {id = 3, name = "Vijai", gender = 1, isClosed = true},
        //                   new People {id = 4, name = "Simi", gender = 2, isClosed = true}
        //               };
        //}
        //else
        //{
        var list = new Collection<People>
                              {
                                  new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
                                  new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
                                  new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
                                  new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
                                  new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
                              };
       
        /// hard coded value passed for demo purpose
        /// Implement you logic :) !!
        return GridData(1, 1, list.Count, list);
    }

    public string GridData(int noOfPages, int startPage, int noOfRecords, Collection<People> list)
    {
        var gridData = new
                           {
                               total = noOfPages,
                               page = startPage,
                               records = noOfRecords,
                               rows = list,
                           };
        
        var jsonSerializer = new JavaScriptSerializer();
        return jsonSerializer.Serialize(gridData);

    }
    


    public class People
    {
        public People()
        {
            Name = string.Empty;
            Id = 0;
            Gender = 0;
            IsClosed = false;
        }



        public string Name { get; set; }
        public int Id { get; set; }
        public int Gender { get; set; }
        public bool IsClosed { get; set; }
    }
    
    public enum Oper
    {
        edit=1,
        del=2,
        add=3
    }





    

</script>
</html>

Open in new window

JQExample.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
    <title>JqGrid</title>
    <link href="themes/redmond/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
    <link href="themes/ui.jqgrid.css" rel="stylesheet" type="text/css" />    
    <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.jqGrid.js" type="text/javascript"></script>
    
</head>
<body>
   <%-- <form id="form1">--%>
    <table id="jsonmap">
    </table>
    <div id="pjmap">
    </div>

    
    <script type="text/javascript">
        
        jQuery("#jsonmap").jqGrid({
            url: 'GetData.aspx',
            datatype: 'json',
            colNames: ['ID', 'Name','Active','Gender'],
            colModel: [{
                    name: 'id',
                    index: 'id',
                    width: 35,
                    editable: false,
                    editoptions: {
                    readonly: true,
                    size: 10
                }},                
                {
                    name: 'name',
                    index: 'name',
                    width: 150,
                    align: "left",
                    editable: true,
                    size: 100
                  },
                {
                    name: 'isClosed',
                    index: 'isClosed',
                    width: 100,
                    align: 'left',
                    editable: true,
                    edittype: "checkbox",
                    editoptions: {
                    value: "true:false",
                    formatter: "checkbox"
                }},
                {
                    name: 'gender',
                    index: 'gender',
                    width: 100,
                    formatter:'select',
                    editable: true,
                    edittype: "select", 
                    editoptions: {value: "0:select;1:male;2:female"}
                }],
                rowNum: 10,
                rowList: [2, 5, 10, 15],
                pager: '#pjmap',
                sortname: 'id',
                sortorder: "desc",
                viewrecords: true, 
                jsonReader: {
                    repeatitems: false
                },
                width: 600,
                caption: 'First jqGrid',
                height: '100%',
                editurl: 'GetData.aspx'
            });


            jQuery("#jsonmap").navGrid("#pjmap", {
                    edit: true,
                    add: true,
                    del: true
                },
                {
                    closeAfterEdit: true,
                    reloadAfterSubmit: false
                },
                {
                    closeAfterAdd: true,
                    reloadAfterSubmit: false
                },
                {
                    reloadAfterSubmit: false
                });



    </script>
      <table id="Jqgrid" width="100%">
    </table>
    <div id="pager"></div> 
    </form>
</body>
</html>

Open in new window

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 500 total points
ID: 36564051
You need to use the right case for the fields : Id, Name, Gender vs id, name and gender in your code
0
 

Author Comment

by:Efremdawit
ID: 36564381
I modified the field case with case sensitive issue. When I updated this, the the data appeared.

Now I want to change the data source and the colNames and colModel accordingly to get the data dynamically.


Script for data format

$(document).ready(function () {
           $.ajax({
                            type: 'POST',
                            contentType: "application/json; charset=utf-8",
                            url: "GetData.aspx",
                            datatype: 'json',
                            success: function (result) {
                               
//                                colD = result.colData;
//                                colN = result.colNames;
                                var colM = result.colModel;
                                 //alert(result.colModel);
                                jQuery("#UsersGrid").jqGrid
                                      (
                                        {
                                            jsonReader: { repeatitems: false, cell: "", id: "0" },
                                            //url: "GetData.aspx", 
                                            datatype: 'json',
                                            mtype: 'POST',
                                            colModel: colM,
                                            
                                           data: colD.rootVar,
                                           ColNames: colN,
                                            ColModel: ColM,
                                            height: "auto",
                                            gridview: true,
                                            pager: '#pager',
                                            rowNum: 5,
                                            rowList: [5, 10, 20, 50],
                                            viewrecords: true,
                                            loadComplete: function (data) {
                                                alert('loaded completely'); 
                                             },
                                            loadError: function () {
                                                alert('error'); 
                                             }
                                        });
                            },
                            error: function (x, e) {
                                alert(x.readyState + ' ' + x.status + e.msg);
                            }
                        });

Then in server side
change the hardcoded list to get the data array. Instead try to use ADO.net (not linq) to connect the data source as a query. In this query try to get total page, total record, order by and PK. Therefore, replace 

var list = new Collection<People>
                              {
                                  new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
                                  new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
                                  new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
                                  new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
                                  new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
                              };
       
        /// hard coded value passed for demo purpose
        /// Implement you logic :) !!
        return GridData(1, 1, list.Count, list);
    }

    public string GridData(int noOfPages, int startPage, int noOfRecords, Collection<People> list)
    {
        var gridData = new
                           {
                               total = noOfPages,
                               page = startPage,
                               records = noOfRecords,
                               rows = list,
                           };
        
        var jsonSerializer = new JavaScriptSerializer();
        return jsonSerializer.Serialize(gridData);

    }
    

So would you please give a sample code to get such task?

Open in new window

0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 37319213
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now