Tuesday 3 April 2012

How to : Get datatable values using jquery from client to server side.

Introduction

First you need to make call from client side to server using below javascript funtion


$.ajax({
                   type: "get",
                   url: "?ajax_mode=GetMyData,
                   dataType: "json",
                   async: false,
                   cache: false,
                   success: function(data, textStatus) {
                       if (data.status == "success") {
                          for (var row, i = 0; row = data.obj[i]; i++) {                               
                                // Process row var for as per usage.
                }
                       }
                       else {

                       }
                   }
               });

Now You need to create class for datatable and you need to define Structure for BasicOuputObject. object of this BasicOuputObject

is sent over from server side to client. as below

VB.net

Class MyData
    Public ID As Integer
    Public Name As String
    Public ContactNo As String
End Class


Public Structure BasicOuputObject
    Dim status As String
    Dim errorMessage As String
    Dim strMessage As String
    Dim obj As Object
End Structure


C#.net

class MyData
{
    public int ID;
    public string Name;
    public string ContactNo;
}
public struct BasicOuputObject
{
    public string status;
    public string errorMessage;
    public string strMessage;
    public object obj;
}

Now you have to use below function for getting datatable in code behind file.

VB.NET
Public Sub GetMyData()

        Dim objOutput As New BasicOuputObject
        Dim objCommand As New SqlCommand
        Dim lstMyData As New List(Of MyData)
        Dim objMyData As MyData
        Dim objConn As New SqlConnection("Pass Connection String")
        objCommand.CommandText = "select ID ,Name ,ContactNo from Customers"
        objCommand.Connection = objConn

        objConn.Open()
        Dim m_rdrReader As SqlDataReader = objCommand.ExecuteReader()
        If m_rdrReader.HasRows Then
            While m_rdrReader.Read()
                objMyData = New MyData
                objMyData.ID = m_rdrReader(0)
                objMyData.Name = m_rdrReader(1)
                objMyData.ContactNo = m_rdrReader(2)
                lstMyData.Add(objMyData)
            End While
        End If
        m_rdrReader.Close()

        objOutput.errorMessage = ""
        objOutput.obj = lstMyData
        objOutput.strMessage = "success"

        Dim objSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
        HttpContext.Current.Response.Write(objSerialiser.Serialize(objOutput))
        HttpContext.Current.Response.End()

    End Sub


End Class


I hope this article was useful and I thank you for viewing it. keep visiting blog , you can get more stuff






No comments:

Post a Comment