Click here to Skip to main content
15,885,309 members
Articles / Web Development / XHTML

ASP.NET 3.5 Sample Application of LINQ, WFC, JSON, and AJAX

Rate me:
Please Sign up or sign in to vote.
3.89/5 (21 votes)
4 Sep 2008CPOL2 min read 135.9K   4.5K   56   9
A simple sample of LINQ, WCF, JSON, and AJAX.

Image 1

Introduction

The purpose of this article is to provide a working sample of a new .NET technologies. This sample contains a working example of calling a WCF service from AJAX and using the results in JavaScript via JSON. It will also provide you with an example of how to call a Stored Procedure in LINQ. This sample uses the Northwind database that you can download from Microsoft. In order to run the sample, you must change the connection string "NorthwindConnectionString" in the web.config to point to your copy of Northwind. The SearchCustomers Stored Procedure code is provided in a text file in the solution.

Background

Often, developers are too busy actually working on applications to take the time to learn all of the new tools provided by Microsoft. I have seen some examples of LINQ, WCF, and JSON, but I wanted to put a simple example of each in one place.

An entity class to use with JSON

The class below is an entity that will be accessible in JavaScript. In order to access the properties via JSON, you need to add the appropriate attributes.

C#
using System;
using System.Runtime.Serialization;
 
namespace WCF_AJAX.Data
{
    [Serializable]
    [DataContract]
    //Take note of the attributes Serializable, DataContract and DataMember
    //These are what make the object easily usable to you via JSON
    public class CustomerItem
    {   

        [DataMember]
        public string CustomerID {get;  set;}

        [DataMember]
        public string ContactName { get; set; }

        public CustomerItem()
        {

        }
    }
}

Accessing the entity object via JSON

The markup file below gives an example of using the list of CustomerItems that is returned from the WCF Service. In order to use the JavaScript below, you need to have a ScriptManager and a reference to the ApplicationService (the WCF).

ASP.NET
<asp:scriptmanager id="ScriptManager1" runat="server">
    <services>
        <asp:servicereference path="~/Services/ApplicationService.svc">
        </asp:servicereference>
    </services>
</asp:scriptmanager>"

The JavaScript:

JavaScript
function Search() {
   var textInput =$get("txtSearch");
   ApplicationService.searchCustomers(textInput.value, OnSearchComplete, OnError);
   $get("ddlCustomers").focus();
}

function OnSearchComplete(result) {
   var selectOfCustomers = $get("ddlCustomers");
   var customerItems = result;
   var pos = 0;
   for (var customerNo in customerItems) {
      var oOption = document.createElement("OPTION");
      oOption.text = customerItems[customerNo].ContactName;
      oOption.value = customerItems[customerNo].CustomerID
      selectOfCustomers.add(oOption, pos);
      pos += 1;
   }
}

function OnError(result) {
   alert(result.get_message());
}

Creating the WCF Service using LINQ to get your data

The class below is the WCF service called from the client. The AspNetCompatibilityRequirements attributes are required.

C#
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;

namespace WCF_AJAX.Services
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = 
         AspNetCompatibilityRequirementsMode.Allowed)]
    public class ApplicationService
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        public List<data.customeritem>searchCustomers(string searchText)
        {
            var listOfCustomerItems = new List<data.customeritem>();
            var dataContext = new Data.NorthwindDataContext();
            foreach (var result in dataContext.SearchCustomers(searchText))
            {
                var item = new Data.CustomerItem();
                item.CustomerID = result.CustomerID;
                item.ContactName = result.ContactName;
                listOfCustomerItems.Add(item);
            }
            return listOfCustomerItems;
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

The NorthwindDataContext class was created by the designer. There is no coding required to create the class. In order to use a Stored Procedure, you have to chose "Add New Item" from the solution and pick LINQ to SQL Classes. VS 2008 will add a DBML file to the project. Then, open the DBML file in design mode and drag the Stored Procedure from the Server Explorer tab's Data Connections.

Image 2

License

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


Written By
Web Developer
United States United States
Life.

Comments and Discussions

 
GeneralLiked your sample Pin
nursiko2-Feb-12 18:50
nursiko2-Feb-12 18:50 
GeneralMy vote of 3 Pin
Pramod k patel24-Nov-11 19:00
professionalPramod k patel24-Nov-11 19:00 
GeneralMy vote of 4 Pin
Tathagat Verma28-Sep-11 1:51
Tathagat Verma28-Sep-11 1:51 
GeneralMy vote of 2 Pin
Jason Ti19-Feb-10 4:13
Jason Ti19-Feb-10 4:13 
QuestionWhat changes need to be done in cross domain case? Pin
prasad v pathak11-Nov-08 1:52
prasad v pathak11-Nov-08 1:52 
QuestionNot getting jsdebug file Pin
prasad v pathak10-Nov-08 22:29
prasad v pathak10-Nov-08 22:29 
GeneralReminder: This Does Not Work Across Domains Pin
Ken Cox18-Oct-08 11:18
Ken Cox18-Oct-08 11:18 
GeneralTitle Pin
PIEBALDconsult4-Sep-08 16:33
mvePIEBALDconsult4-Sep-08 16:33 
GeneralRe: Title Pin
ToddHileHoffer5-Sep-08 2:07
ToddHileHoffer5-Sep-08 2:07 

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.