jqGrid in asp.net

Last post 10-01-2009 4:08 PM by rumenstankov. 13 replies.

Sort Posts:

  • jqGrid in asp.net

    06-01-2009, 2:31 PM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    Hello Friends,

                         I managed to use the jqGrid in asp.net using WebService. Here is the code I've used:

     

    <script type="text/javascript" src="jqGrid-3.4.3/jquery-1.3.1.js"></script>
    
    <script type="text/javascript" src="jqGrid-3.4.3/jquery.jqGrid.js"></script>
    
    <script type="text/javascript" src="jqGrid-3.4.3/js/jqModal.js"></script>
    
    <script type="text/javascript" src="jqGrid-3.4.3/js/jqDnR.js"></script>
    
    <link href="jqGrid-3.4.3/themes/coffee/grid.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">
            jQuery(document).ready(function() {
                $('#list').jqGrid({
                    datatype: function() {
                        $.ajax({
                            url: "jqGrid.asmx/NewMethod",
                            data: "{}",  // For empty input data use "{}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            complete: function(jsondata, stat) {
                                if (stat == "success") {
                                    var thegrid = jQuery("#list")[0];
                                    thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
                                }
                            }
                        });
                    },
                    colNames: ['ID', 'Name', 'Location'],
                    colModel: [
              { name: 'ID', index: 'ID', width: 80, align: 'left', editable: false },
              { name: 'Name', index: 'Name', width: 120, align: 'left', editable: true},
              { name: 'Location', index: 'Location', width: 60, align: 'left', editable: true, edittype: "select", editoptions: { value: "FE:FedEx; IN:InTime; TN:TNT"}}],
                    pager: jQuery('#pager'),
                    rowNum: 5,
                    rowList: [10, 20, 30],
                    sortname: 'Name',
                    sortorder:'desc',
                    viewrecords: true,
                    imgpath: 'jqGrid-3.4.3/themes/coffee/images',
                    caption: 'jqGrid First Grid',
                    width: 300
                  }).navGrid(pager, { edit: true, add: false, del: false, search: false });
            }); 
        </script>
    
    <body>
        <table id="list" class="scroll" cellpadding="0" cellspacing="0">
        </table>
        <div id="pager" class="scroll" style="text-align: center;">
        </div>
    </body>

      

    WebMethod:

      

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Services;
    using System.Web.Script.Services;
    using System.Web.Script.Serialization;
    using System.Diagnostics;
    using System.Data;
    using System.Text;
    using System.Data.SqlClient;
    
    public class SecondMethod
    {
        public string total;
        public string page;
        public string records;
        public RowElement[] rows;
    }
    
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class jqGrid : System.Web.Services.WebService
    {
        Random rndID = new Random(DateTime.Now.Millisecond);
        Random rndChar = new Random(DateTime.Now.Millisecond);
        SqlConnection conn = new SqlConnection(@"Server = .\SQLExpress; Initial Catalog = Test; Integrated Security = True");
       
        [WebMethod]
        public SecondMethod NewMethod()
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select * from Test", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            SecondMethod sem = new SecondMethod();
            sem.total = "1";
            sem.page = "1";
            sem.records = "5";
            dt.TableName = "Test";
            int iRowCount = dt.Rows.Count;
            dt.DefaultView.Sort = "Name";
            DataView dv = dt.DefaultView;
            dt = dv.ToTable();
            sem.rows = new RowElement[iRowCount];
            for (int iCount = 0; iCount < iRowCount; iCount++)
            {
                sem.rows[iCount] = new RowElement();
                sem.rows[iCount].id = Convert.ToString(iCount + 1);
                sem.rows[iCount].cell = new string[3];
                sem.rows[iCount].cell[0] = dt.Rows[iCount]["ID"].ToString();
                sem.rows[iCount].cell[1] = dt.Rows[iCount]["Name"].ToString();
                sem.rows[iCount].cell[2] = dt.Rows[iCount]["Location"].ToString();
            }
    
            return sem;
        }
    }
    
    
    I'm pretty sure that the method I've used to bind the data is not appropriate, but still since this is my first grid, I had to use it.
     
    Now my question is,  I was not able to Sort the columns using the above scripts. 
    So I got a tip that I should use ashx file to make jqGrid more effective and efficient. I'm not quite familiar with ashx(IHttpHandler) concept. 
    Can any one tell me how to use ashx file to bind jqGrid in asp.net? Or give me a brief intro about ashx concept?
     
     
    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    06-14-2009, 8:52 AM
    • Member
      7 point Member
    • bluebirdzx
    • Member since 05-06-2006, 6:41 AM
    • Posts 2

    hi, it is ok with IHttpHandler,you may try it, but my code  have some bug, next page  and pre page is bad.

     

                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                context.Response.AddHeader("pragma", "no-cache");
                context.Response.AddHeader("cache-control", "");
                context.Response.CacheControl = "no-cache";
                context.Response.ContentType = "text/plain"; 
               
                 int page = 1;
                 if (HttpContext.Current.Request.Form["page"] != null)
                {
                   
                    page = int.Parse(HttpContext.Current.Request.Params["page"].ToString());
                }
                 int rows = 10;
                if (HttpContext.Current.Request.Form["rows"] != null)
                {
                    rows = int.Parse(HttpContext.Current.Request.Form["rows"].ToString());
                }
      
                string sidx = "Name";
                if (HttpContext.Current.Request.Form["sidx"] != null)
                {
                    sidx = HttpContext.Current.Request.Form["sortname"].ToString();
                }
                string whereCondition = "";
                //if (HttpContext.Current.Request.Form["qtype"] != null && HttpContext.Current.Request.Form["query"] != null && HttpContext.Current.Request.Form["query"].ToString() != string.Empty)
                //{
                //    whereCondition = BuildWhereCondition(HttpContext.Current.Request.Form["qtype"].ToString(), HttpContext.Current.Request.Form["query"].ToString());
                //}
    
                string sord = "asc";
                if (HttpContext.Current.Request.Form["sord"] != null)
                {
                    sord = HttpContext.Current.Request.Form["sord"].ToString();
                }
                string sortExp = sidx + " " + sord;
                int start = ((page - 1) * rows);
               
                DataAccess newDataAccess = new DataAccess();
                List<Product> data = newDataAccess.GetAllProducts(whereCondition, sortExp, start, rows);
                JavaScriptDateTimeConverter aa = new JavaScriptDateTimeConverter();
                
               
                string strlist = Newtonsoft.Json.JsonConvert.SerializeObject(data,new JavaScriptDateTimeConverter());
    
                string ttt="";
                for (int j = 0; j < HttpContext.Current.Request.Form.Count; j++)
                {
                    ttt += "--" + HttpContext.Current.Request.Form[j];
                }
                System.IO.File.WriteAllText("d:\\aaab.txt", HttpContext.Current.Request.Form["page"] + "===" + page.ToString() + "-----" + start.ToString() + "---" + sortExp + "-" + rows);
                int totalpage = newDataAccess.TotalRows / rows + 1;
            
                string str = "{totalpages: \"" + totalpage.ToString() + "\",";
                       str +="currpage: \"" + page.ToString() + "\",";
                       str +="totalrecords: \"" + newDataAccess.TotalRows.ToString() +"\",rows : ";
                // one way demo
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]},";
                //str += "{id:\"1\", cell:[\"1\", \"sdd\", \"2009-05-06\",\"dfdf\",\"dfdff\",\"78\"]}";
                //second way demo
               // str += "{Id:6,Name:\"6565\",Description:\"6565\",Unit:\"6565\",UnitPrice:6565,CreateDate:\"2009-6-5\"},";
               // str += "{Id:6,Name:\"6565\",Description:\"6565\",Unit:\"6565\",UnitPrice:6565,CreateDate:\"2009-6-5\"}]}";
                    str += strlist +"}";
                    context.Response.Write(str);

      

    HTML code is

     

    jQuery(document).ready(function() {
            jQuery("#west-grid").jqGrid({
                url: 'Handler1.ashx',
                datatype: 'json',
                type: "POST", 
                jsonReader: {
                    root: "rows",
                    page: "currpage",
                    total: "totalpages",
                    records: "totalrecords",
                    repeatitems: false,
                    id: "0"
                },
    
                colNames: ['Id', 'Name', 'Description', 'Unit', 'UnitPrice', 'CreateDate'],
                colModel: [
          { name: 'Id', index: 'Id', width: 55 },
          { name: 'Name', index: 'Name', width: 90, editable: true },
          { name: 'Description', index: 'Description', width: 80, align: 'right', editable: true },
          { name: 'Unit', index: 'Unit', width: 80, align: 'right', editable: true },
          { name: 'UnitPrice', index: 'UnitPrice', width: 80, align: 'right', editable: true },
          { name: 'CreateDate', index: 'CreateDate', width: 150, date: true, datefmt: 'Y-m-d', sortable: false, editable: true}],
                pager: jQuery('#pager'),
                rowNum: 10,
                rowList: [10, 20, 30],
                sortname: 'id',
                sortorder: "desc",
                root: "rows",
                page: "currpage",
                total: "totalpages",
                records: "totalrecords",
                repeatitems: false,
                id: "0",
                viewrecords: true,
                imgpath: 'themes/basic/images',
                caption: 'My first grid'
    
            });
            jQuery("#west-grid").navGrid('#Pager', {
                edit: true, add: true, del: true, search: true
            }).navButtonAdd('#Pager', {
                caption: "Add", buttonimg: "fullpath/row_add.gif", onClickButton: function() { alert("Adding Row") }, position: "last"
            }).navButtonAdd('#Pager', {
                caption: "Del", buttonimg: "fullpath/row_del.gif", onClickButton: function(id) { alert("Deleting Row: " + id) }, position: "last"
            });
      
  • Re: jqGrid in asp.net

    06-14-2009, 11:19 AM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    Yeah, thanks man. I too tried a bit and made it working in Handler. Its just superb and fast than XML as far as I've seen, but dunno about the drawbacks in it. You have any idea? 

    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    06-24-2009, 2:02 PM
    • Member
      6 point Member
    • bosasj
    • Member since 06-16-2009, 4:01 PM
    • Posts 3

     This may seem out of place but what namespace is the RowElement class found? Thanks in advance.

  • Re: jqGrid in asp.net

    06-24-2009, 2:16 PM
    • Member
      6 point Member
    • bosasj
    • Member since 06-16-2009, 4:01 PM
    • Posts 3

    I'm assuming it is some type of custom class rather than one defined in .Net but I just wanted to check just to make sure.

  • Re: jqGrid in asp.net

    06-25-2009, 12:25 AM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    RowElement is a class which contains following:

    public class RowElement
    {
        public string id;
        public string[] cell;
    }


    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    06-25-2009, 9:48 AM
    • Member
      6 point Member
    • bosasj
    • Member since 06-16-2009, 4:01 PM
    • Posts 3

    Yup, that makes complete sense. I don't know if you are still interested, but I found a link that I thought you may be interested in. The example is in xml but may still be useful to you. Oh, and thank you for the quick reply.

    Link: http://netindonesia.net/blogs/cipto/archive/2009/04/03/jqgrid.aspx 

  • Re: jqGrid in asp.net

    06-25-2009, 10:42 AM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    Yeah, I did an example with XML by seeing this link. But I experienced, JSON is faster than XML.

    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    06-29-2009, 10:22 PM
    • Member
      4 point Member
    • techgeneis
    • Member since 06-30-2009, 2:20 AM
    • Posts 2

    I have found an article with fully functional example here,

    http://arahuman.blogspot.com/2009/06/jqgrid-using-mvc-json-and-datatable.html

  • Re: jqGrid in asp.net

    08-04-2009, 12:54 PM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    Yeah, that was a good link. You have any idea, where we can load the DropDownList in a row dynamically from Database?

    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    08-10-2009, 5:44 AM
    • Member
      5 point Member
    • centrium777
    • Member since 06-10-2008, 11:39 AM
    • Posts 7

    Hi Everyone


    I am looking to achieve what you have done here, but unforuntatly I cannot get it to work, I have implemented your code in my webservice an returning back the sem object which I get the following JSON response

    {"d":{"__type":"jqGridData","total":"1","page":"1","records":"1","rows":[{"id":"1","cell":["45","5","140"]},{"id":"2","cell":["45","5","140"]},{"id":"3","cell":["45","5","140"]}]}}

    I run this through a json parser and the json looks fine, however when I try and bind this to the grid (again using your code) it doesnt display anything on the grid and there are no error

    The only difference I guess is I am using the 3.5 version of jqgrid instead of 3.4.3

    Apolgies if this is posted on the asp.net forum but your the closest I've found to anyone addressing this issue.


    Cheers


    Cent

  • Re: jqGrid in asp.net

    08-10-2009, 11:23 AM
    • Contributor
      2,923 point Contributor
    • engineerachu
    • Member since 10-24-2007, 12:05 PM
    • Madurai/Chennai, TamilNadu, India
    • Posts 804

    Have a look at this link http://praveen1305.blogspot.com/2009/05/jqgrid-with-asp-net-web-forms.html. Initially, I tried a sample from this site and later made a sample of my own. If you don't get a solution, please let me know, I'll give you my sample. I use jqGrid 3.5. The problem might be in your script. Can you post your code, please?

    Cheers,
    Achutha Krishnan

    ~ In order to succeed, your desire of success should be greater than your fear of failure ~
  • Re: jqGrid in asp.net

    08-10-2009, 4:45 PM
    • Member
      5 point Member
    • centrium777
    • Member since 06-10-2008, 11:39 AM
    • Posts 7

    Thanks for the reply mate and good pointer with the link.


    I actually narrowed down the problem, eventually after several days and was due to the fact I hadn't put the locale.js file in the correct order before the jqgrid.js file

    Kinda silly mistake for not following the example to the letter on the jqgrid wiki, however we live and learn I guess.


    Cheers for help though.

  • Re: jqGrid in asp.net

    10-01-2009, 4:08 PM
    • Member
      2 point Member
    • rumenstankov
    • Member since 10-01-2009, 4:04 PM
    • Posts 1

    Just to let you know, we (the guys behind jqGrid) started a beta project for jqGrid integration with ASP.NET. The approach we’ve taken is to create a server-side component, pretty much similar to what you are using to with asp:GridView (similar programming/event model and APIs)

    Demo can be found here:
    http://www.trirand.net/demo.aspx

    Download bits and samples are also available.

    Cheers,
    Rumen Stankov
    jqGrid

    Filed under: , , ,
Page 1 of 1 (14 items)