Click here to Skip to main content
14,027,272 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

16.4K views
4 bookmarked
Posted 11 Oct 2013
Licenced CPOL

jqGrid and ASP.Net Web Forms

, 11 Oct 2013
Rate this:
Please Sign up or sign in to vote.
I have been getting the hang of using jqGrid from with asp.net web forms.  So I will to  brief walkthru.first add the following HTML to your

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

I have been getting the hang of using jqGrid from with asp.net web forms.  So I will to  brief walkthru.

first add the following HTML to your page:

<table id="list4"></table>
<div id="gridpager"></div>

Now in your docready function or a function you plan to load the grid in add the following code:

$("#list4").jqGrid({
datatype: "local",
height: 250,
loadtext: "Loading...",
colNames: ['Col1', 'Col2', 'Col3'],
colModel: [
     { name: 'Col1', index: 'Col1', hidden: true },
     { name: 'Col2', index: 'Col2', sorttype: "text" },
     { name: 'Col3', index: 'Col3', width: 100, sorttype: "text"  }
   ],
multiselect: false,
pager: '#gridpager',
pgbuttons: false,
pgtext: null,
recordtext: '',
viewrecords: true,
autowidth: true,
caption: "Summary"
});
$("#list4").navGrid('#gridpager',
{view:false,edit:false,search:true,add:false,del:false,refresh:false}
);

var dArray = "{";
dArray += "'userid': '" + <%=Page.User.Identity.Name %> + "',";
dArray += "'fromdate': '" + $("#<%= txtFrom.ClientID %>").val() + "',";
dArray += "'todate': '" + $("#<%= txtTo.ClientID %>").val() + "'";
dArray += "}";

$.ajax({
type: "POST",
url: "default.aspx/GetGridData",
data: dArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
    //$("#list4").clearGridData();
    var gd = eval('(' + response.d + ')');
    for (row in gd){
 $("#list4").jqGrid('addRowData', row, gd[row]);
    }
},
error: function (response) {
    alert(response.responseText);
}
});

Now I would say to use a web service but Ihave certain pages where this is just a one of so I amusing PageMethods here.  Create your Pagemethod to return the data as a JSON string.  i will also provide a helper utility to convert a dataTable to a JSON string.

'pagemethod
 <WebMethod()> _
    Public Shared Function GetGridData(userid As String, fromdate As String, todate As String) As String
        Dim result As String = String.Empty
        Try
            Dim params As New List(Of SqlParameter)
            params.Add(New SqlParameter("userid", userid))
            params.Add(New SqlParameter("from", String.Format("{0} 12:00 AM", fromdate)))
            params.Add(New SqlParameter("to", String.Format("{0} 11:59 PM", todate)))
            Using dt As DataTable = SqlHelper.GetDataTable("stp_getSomeGridDataProcedure", CommandType.StoredProcedure, params.ToArray)
                result = ConvertDataTableToJSON(dt)
            End Using

        Catch ex As Exception

        End Try

        Return result
    End Function
   

and the helper function:

'utility function to convert datatable to json
Public Shared Function ConvertDataTableToJSON(Dt As DataTable) As String

        Dim StrDc As String() = New String(Dt.Columns.Count) {}
        Dim HeadStr As String = String.Empty
        Dim hdrLst As New List(Of String)
        For i As Integer = 0 To Dt.Columns.Count - 1
            StrDc(i) = Dt.Columns(i).Caption
            hdrLst.Add("""" + StrDc(i) + """ : """ + StrDc(i) + i.ToString() + "¾" + """")
        Next
        HeadStr = Join(hdrLst.ToArray, ",")
        Dim Sb As New StringBuilder()
        Sb.Append("{""" + Dt.TableName + """ : [")
        For i As Integer = 0 To Dt.Rows.Count - 1
            Dim TempStr As String = HeadStr
            Sb.Append("{")
            For j As Integer = 0 To Dt.Columns.Count - 1
                Dim replaceString As String = Dt.Columns(j).ToString & j.ToString() & "¾"
                Dim newString As String = Dt.Rows(i)(j).ToString()
                TempStr = TempStr.Replace(replaceString, newString)
            Next
            Sb.Append(TempStr + "},")
        Next

        Sb = New StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1))
        Sb.Append("]}")

        Return Sb.ToString()
    End Function

Remember to update the column names and the sql to reflect your data.  Hope this helps someone else.  Oh, this is using the datatype="local", you could easily move the ajax call into the datatype as a fucntion as such:

datatype: function (pdata) {
 var dArray = "{";
 dArray += "'userid': '" + <%=Page.User.Identity.Name %> + "',";
 dArray += "'fromdate': '" + $("#<%= txtFrom.ClientID %>").val() + "',";
 dArray += "'todate': '" + $("#<%= txtTo.ClientID %>").val() + "'";
 dArray += "}";

 $.ajax({
  type: "POST",
  url: "default.aspx/GetGridData",
  data: dArray,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  async: true,
  success: function (response) {
   //$("#list4").clearGridData();
   var gd = eval('(' + response.d + ')');
   for (row in gd){
    $("#list4").jqGrid('addRowData', row, gd[row]);
   }
  },
  error: function (response) {
   alert(response.responseText);
  }
 });
},

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ASP.NET Community
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
Group type: Collaborative Group

760 members


You may also be interested in...

Comments and Discussions

 
QuestionHelpful Pin
sachin.raikar9-Aug-14 18:02
membersachin.raikar9-Aug-14 18:02 
QuestionPagination Jqgrid Pin
grofol16-Oct-13 10:22
membergrofol16-Oct-13 10:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190419.4 | Last Updated 11 Oct 2013
Article Copyright 2013 by ASP.NET Community
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid