Solved

Handling JSON Array returned from ASP.NET Web Service with jQuery

Posted on 2013-06-10
2
1,990 Views
Last Modified: 2013-06-10
Hi experts,

I'm using Visual Studio 2010, asp.net and VB as the code behind language.
I'm also using Sql server 2008 and Jquery for this example.

So I read this example, the example in this link is in C# but I'm doing mine in VB:
http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

So here are the steps do this example:

--------------------------------------------------------------------------------------------------------------------
Step 1    Create the SQL Server Table

Step 2    Create Web Service that outputs JSON array

Step 3    Create asp.net page that contains jquery code that calls JSON array from the Web Service created in step 2.

Step 4          Run Application
--------------------------------------------------------------------------------------------------------------------



Ok so here is what I have so far.

Step 1      Create the SQL Server Table

I created a sql server table called Cars

This is the code to create the table:

CREATE TABLE [dbo].[Cars](
	[Make] [varchar](50) NULL,
	[Model] [varchar](50) NULL,
	[Year] [int] NULL,
	[Doors] [int] NULL,
	[Color] [varchar](50) NULL,
	[Price] [money] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Audi', N'A4', 1995, 5, N'Red', 3189.2300)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Ford', N'Focus', 2002, 5, N'Black', 3460.7600)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'BMW', N'5 Series', 2006, 4, N'Grey', 26568.0100)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Renault', N'Laguna', 2000, 5, N'Red', 4254.0800)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Toyota', N'Previa', 1998, 5, N'Green', 2869.7700)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Mini', N'Cooper', 2005, 2, N'Grey', 10488.7700)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Mazda', N'MX 5', 2003, 2, N'Silver', 7448.6300)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Ford', N'Fiesta', 2004, 3, N'Red', 4002.7700)
INSERT [dbo].[Cars] ([Make], [Model], [Year], [Doors], [Color], [Price]) VALUES (N'Honda', N'Accord', 1997, 4, N'Silver', 2124.3800)

Open in new window


Once I created the table, now I need to create the Web Service.

Step 2      Create Web Service that outputs JSON array

I created a .asmx WebService called CarsWebServiceJSON1.asmx

This is the code for  it:


Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web
Imports System.Web.Script.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Collections.Generic
Imports System.Runtime.Serialization.Json
Imports System.IO
Imports System.Text
 
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class CarsWebServiceJSON1
    Inherits System.Web.Services.WebService
 
    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function
 
 
    ' This method returns a Json type.
    <WebMethod()> _
    <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetAllCars() As List(Of Car)
        'Dim reports As New List(Of ModelReport.Report)()
        Dim reports As New List(Of Car)()
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("TestDatabaseConnectionString").ConnectionString
        Using connection As New SqlConnection(connectionString)
            Using command As SqlCommand = connection.CreateCommand
                Dim sql As String = "SELECT [Make],[Model],[Year],[Doors],[Color],[Price] FROM [TestDatabase].[dbo].[Cars]"
                connection.Open()
 
                command.CommandText = sql
                Using reader As SqlDataReader = command.ExecuteReader()
                    While reader.Read()
                        'Dim report As New ModelReport.Report()
                        Dim report As New Car()
                        report.Make = reader("Make").ToString()
                        report.Model = reader("Model").ToString()
                        report.Year = reader("Year").ToString()
                        report.Doors = reader("Doors").ToString()
                        report.Color = reader("Color").ToString()
                        report.Price = reader("Price").ToString()
                        reports.Add(report)
                    End While
                End Using
            End Using
        End Using
 
        Return reports
    End Function
 
    <WebMethod()> _
    Public Function GetCarsByDoors(doors As Integer) As List(Of Car)
 
        'Dim reports As New List(Of ModelReport.Report)()
        Dim reports As New List(Of Car)()
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("TestDatabaseConnectionString").ConnectionString
        Using connection As New SqlConnection(connectionString)
            Using command As SqlCommand = connection.CreateCommand
                Dim sql As String = "SELECT [Make],[Model],[Year],[Doors],[Color],[Price] FROM [TestDatabase].[dbo].[Cars]"
                connection.Open()
 
                command.CommandText = sql
                Using reader As SqlDataReader = command.ExecuteReader()
                    While reader.Read()
                        'Dim report As New ModelReport.Report()
                        Dim report As New Car()
                        report.Make = reader("Make").ToString()
                        report.Model = reader("Model").ToString()
                        report.Year = reader("Year").ToString()
                        report.Doors = reader("Doors").ToString()
                        report.Color = reader("Color").ToString()
                        report.Price = reader("Price").ToString()
                        reports.Add(report)
                    End While
                End Using
            End Using
        End Using
 
        Dim query = From c In reports Where c.Doors = doors
 
        Return query.ToList()
 
    End Function
 
 
End Class
 
 
Public Class Car
    ' String type
    Private privateMake As String
    Public Property Make() As String
        Get
            Return privateMake
        End Get
        Set(ByVal value As String)
            privateMake = value
        End Set
    End Property
    ' String type
    Private privateModel As String
    Public Property Model() As String
        Get
            Return privateModel
        End Get
        Set(ByVal value As String)
            privateModel = value
        End Set
    End Property
    ' Integer type
    Private privateYear As Integer
    Public Property Year() As Integer
        Get
            Return privateYear
        End Get
        Set(ByVal value As Integer)
            privateYear = value
        End Set
    End Property
    ' Integer type
    Private privateDoors As Integer
    Public Property Doors() As Integer
        Get
            Return privateDoors
        End Get
        Set(ByVal value As Integer)
            privateDoors = value
        End Set
    End Property
    ' String type
    Private privateColor As String
    Public Property Color() As String
        Get
            Return privateColor
        End Get
        Set(ByVal value As String)
            privateColor = value
        End Set
    End Property
    ' String type
    Private privatePrice As String
    Public Property Price() As String
        Get
            Return privatePrice
        End Get
        Set(ByVal value As String)
            privatePrice = value
        End Set
    End Property
End Class

Open in new window


When I run CarsWebServiceJSON1.asmx by viewing it in the browser I get this:

Methods in my WebService
So my web service contains 3 Methods. The Method I want to use for my example is the method called GetAllCars()

If I click on the GetAllCars link then I get this:

the output of my GetAllCars method
So my Web Service method is working correct.

So now I want to create an asp.net page where I can just Jquery to call array returned by the GetAllCars method.

Step 3     Create asp.net page that contains jquery code that calls JSON array from the Web Service created in step 2.


So now I create a page called GetCarsWebServiceJSON1.aspx

This is the code I have for GetCarsWebServiceJSON1.aspx:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="GetCarsWebServiceJSON1.aspx.vb" Inherits="JServices.GetCarsWebServiceJSON1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
<script type="text/javascript" src="Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
 
    $(function () {
        $('#Button1').click(getCars);
    });
 
    function getCars() {
 
        $.ajax({
            type: "POST",
            url: "CarWebServiceJSON1.asmx/GetAllCars",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var cars = response.d;
 
                $('#output').empty();
 
                $.each(cars, function (index, car) {
 
                    $('#output').append('<p><strong>' + car.Make + ' ' +
                                car.Model + '</strong><br /> Year: ' +
                                car.Year + '<br />Doors: ' +
                                car.Doors + '<br />Colour: ' +
                                car.Colour + '<br />Price: ' +
                                car.Price + '</p>');
 
                });
 
            },
 
            failure: function (msg) {
                $('#output').text(msg);
            }
 
        });
 
    }
 
</script>
</head>
<body>
<form id="form1" runat="server">
 
<input type="button" id="Button1" value="Get Cars" />
 
<div id="output"></div>
 
</form>
</body>
</html>

Open in new window


This is the code I have for GetCarsWebServiceJSON1.aspx.vb:

Public Class GetCarsWebServiceJSON1
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
    End Sub
 
End Class

Open in new window


So at this point my project directory looks like this:

my app directory in Visual Studio 2010
Step 4          Run Application

So now when I run the application I get this:

when I run my asp page
but if I click the Get Cars button nothing happens.

I should be getting something like the image below.
I think the problem is in my getCars jquery function. I think i'm not writing the data property  correctly.

Can anyone help? Where am I making a mistake in my jquery code.

what I should be getting
0
Comment
Question by:maqskywalker
2 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
Comment Utility
I copied all your code and encountered only 2 small issues:

1) where it says "uncomment the following line", you didn't do that (you have remove the single quote to activate the ScriptService directive)

2) in your ajax call you misspelled CarsWebServiceJSON1.asmx: missing the first 's'
0
 
LVL 1

Author Closing Comment

by:maqskywalker
Comment Utility
thanks. it worked
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Hi all! Recently there was EE question and the person wanted to have a multi-column textbox <div> selection, so as a first step to answer I provided a link but that was not complete with JavaScript selection, but had a good style sheet. So as a ques…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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…

762 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

10 Experts available now in Live!

Get 1:1 Help Now