Home | Projects | Tutorials | Articles | live chat | Submit Project | Big Vote
 
Ajax Projects
.NET Frameworks
Java Frameworks
PHP Frameworks
Ruby Frameworks
Other Frameworks
Cool AJAX sites
Ajax Resources
Ajax Tools
JavaScript frameworks
Partners
AJAX Development

Hight quality AJAX development at low prices

eBuddy

eBuddy articles and instant messenger tips

Stock Exchange Chat

Stock exchange community, chat room for each quote

Web 2.0 Sites

Web 2.0 reviews, articles, cool sites, screenshots, tips...

Self Imrovement

Videos for self improvement, self help, communication skills

Self Help

Articles for self improvement, self help, communication skills

Facebook Applications

Do you want to know the latest facebook applications?

cotton products

Visit Aqttan online store for famous egyptian cotton home textile products.

 Home /  Tutorials / Using ASP.NET AJAX 3.5 JSON Web Services

Using ASP.NET AJAX 3.5 JSON Web Services





JSON Web Services really are the jumping off point between server-centric and client-centric web development. You can add all of the pretty, JavaScript-y, AJAX-y sugar you want to your UI, but if your page or control posts back, (weather or not it is asy

Read The Full Tutorial.



JSON Web Services really are the jumping off point between server-centric and client-centric web development.  You can add all of the pretty, JavaScript-y, AJAX-y sugar you want to your UI, but if your page or control posts back, (weather or not it is asynchronously via an Update Panel) then it is still server-centric in terms of logic.

But by off-loading your logic to JSON Web Services, (as I introduced in Part 1 here) you are making your pages themselves each act like a nice client-centric MVC application.  The HTML is obviously the view, the web services act as the model, since they will be processing business objects for persistence or returning them to the UI for consumption.  Finally, a JavaScript file sits in between, acting as a controller.

Let's break it down with some code, then some discussion:

1.  Model - Web Service

using System;
using System.Web.Services;
using System.Web.Script.Services;

namespace WebApplication1
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class JSONTestService : WebService
    {
        [WebMethod]
        public void SetTest(Guid id, string text)
        {
            this.Application.Add(id.ToString(), text);
        }
        [WebMethod]
        public string GetTest(Guid id)
        {
            return this.Application[id.ToString()].ToString();
        }
        [WebMethod]
        public Guid CreateNew()
        {
            return Guid.NewGuid();
        }
    }
}

Granted, this is only an example, but normally, these web services will be processing full business objects.  What I do is actually keep a variable on the client that stores my object, manipulate its properties via client-side events, (both of which are in the JavaScript file), and then pass the whole object to a web service for server-side manipulation.

So for this example, I'll use a guid as by business object.

2. View - Page / Control Markup

<script type="text/javascript" language="javascript"> 
    var txtGetTestID = '<% =this.txtGetTest.ClientID %>';
    var txtSetTestID = '<% =this.txtSetTest.ClientID %>';
</script>

<table>
    <tr>
        <td>
            &nbsp;
        </td>
        <td>
            <asp:Button id="btnNew" runat="server" Text="New" OnClientClick="GetNew(); return false;" />
        </td>
    </tr>
     <tr>
        <td>
            <asp:TextBox ID="txtSetTest" runat="server" />
        </td>
        <td>
            <asp:Button ID="btnSetTest" runat="server" Text="Set" OnClientClick="SetTest(); return false;" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txtGetTest" runat="server" />
        </td>
        <td>
            <asp:Button ID="btnGet" runat="server" Text="Get" OnClientClick="GetTest(); return false;" />
        </td>
    </tr>
</table>

The only embedded JavaScript here is for variable declarations.  Loose JavaScript files can't use the <% ... %> construct to call into .NET code, since they are not in the context of a page or control.  So I like to expose the controls I'll need to manipulate this way, and then use $get(<control unique id>) in my JavaScript file to get a reference to the control.

NOTE: you can still use server controls, and take advantage of the extensions they add to HTML controls.  However, we don't want to cause a post  back, as that will kill the state of our client objects.  So for controls that always do an AutoPostBack, (like buttons) add "return false;" to end of the "client" event; this will not call __doPostback() behind the scenes.

3. Controller - JavaScript file

var _guid = null;

function GetNew()
{
    WebApplication1.JSONTestService.CreateNew(GetNewDone, OnError, null);
}

function GetNewDone(result)
{
    _guid = result;
}

function SetTest()
{
    WebApplication1.JSONTestService.SetTest(_guid, $get(txtSetTestID).value, null, OnError, null);
}

function GetTest()
{
    WebApplication1.JSONTestService.GetTest(_guid, GetTestDone, OnError, null);
}

function GetTestDone(result)
{
    $get(txtGetTestID).value = result;
}

function OnError(ex)
{
    alert('Error: ' + ex._message);
}

If any of the server code in a web method on your web service throws an exception, the OnError JavaScript function here will be called.  The variable passed is a JSON serialized Exception object, providing the description of the error, as well as a full stack trace!  This way, you can still catch-and-log-and-rethrow your exceptions on the server, and gracefully deal with them on the client.

Another benefit to using a loose JavaScript file as the controller is that it provides a rich debugging experience.  I wrote more about that here.

I know that using a JavaScript file as a controller in the MVC architecture is a stretch, but it works.  Since you can swap .js files on the fly, they are kind of a configurable broker; as long as they handle events on the client and can, in response, call services on the server, the paradigm fits.  This way, you can completely replace your back end, and then merely tweak your JavaScript file to keep communication between your persistence and your UI flowing.

The only thing left to do is wire everything up in the code-behind of the page / control:

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class JSONTest : UserControl //or Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                ScriptManager sm = ScriptManager.GetCurrent(this.Page);
                sm.Scripts.Add(new ScriptReference("/JSONTest.js"));
                sm.Services.Add(new ServiceReference("/JSONTestService.asmx"));
            }
        }
    }
}

And guess what: that might be all the code you need write in your page!  In fact, since I've adopted this architecture, the only code-behind my pages and controls have is in the Load event, if IsPostBack is false.  This separation of logic from presentation makes for a much cleaner ASPX / ASCX file, both in terms of managed code behind and HTML!

Despite the fact that the implementation of the "model" web services is still .NET code, they are called asynchronously though the AJAX web service infrastructure, not via a form submit, and therefore do not cause the Load event of your page to fire.  This really does away with the page lifecycle as we know it. This way, we can move all of the business logic from the page to JavaScript, and then use JSON Web Services to either do persistence and call other services, or do any processing that is too complex for, or not supported by, JavaScript (for example, guids).

Speaking of the implementation of these web methods, there is more thing to point out.  In the first post I linked to in this article, I talk about one main "reality check" of JSON Web Services: they do not share the same Session as the UI.  So my workaround for this is to use the Application object, and store objects in it keyed off of guids.

This way, although all of instances of our app are using the same Application object, there will be no name collisions.  And as far as the server is concerned, and object in memory is an object in memory; there shouldn't be any performance ramifications using this method verses using Session state.

All you have to do is keep track of your guid on the client, and dispose of objects when you're done using them on the server.  The Cache object, with it's built-in expirations, might be even a better option.  The best way to go, however, would be to write a custom module for this type of persistence; using the Application object, however, has worked out fine for me so far.

In conclusion, this is probably the closest we will come to having the client directly call .NET code on-the-fly before SilverLight takes over the web.  But until we are all speaking XAML, consider my client MVC architecture, especially if your page is doing a lot of animation or dynamic control creation.  Moving as much logic from managed code and embedded JavaScript to script controls and JSON Web Services can really make your pages dazzle.

source: catalystss

Related Tutorials

  • Graceful handling of anchors with jQuery
    I've come to use this quite often which eventually leads to a considerable amount of if statements.
  • Nitty Gritty Ajax
    If you hang out with designers and developers at all, then you've probably heard the term "Ajax" by now. It's the official buzzword of Web 2.0. But it's also an extremely useful web development technique.
  • Ajax Beginners Tutorial
    A cross platform tutorial for beginners, it's useful if you don't know how to use Ajax technology, it's recommended to start with this tutorial...
  • Slide In RSS items
    rss-scroller.html = The main HTML you open in your browser js/ajax.js = Ajax (Library from http://twilightuniverse.com/projects/sack) readRSS.php = File that reads RSS data from a source. rss-box.html uses Ajax to retreve data from this file.
  • HTML5 Media Support: video and audio tags
    WebKit keeps on trucking and has added support for the HTML 5 media tags such as
  • JSON Pickle: Serialize your complex Python objects to JSON
    John Paulett wanted to be able to define complex Python model objects, then seamlessly pass them into CouchDB and to client-side Javascript.
Brian cody Says:
Mon Oct 06, 2008 2:09 pm
djladsjalkdjsalkdjajdlksda
Says:
Thu Oct 09, 2008 11:05 pm

Leave Your Comment

Name (Required)
Mail (will not be published) (required)
Website
Top Projects
e-messenger
MSN Web Messenger
ebuddy
MessengerFX
ILoveIM
AJAX file upload
You Tube
KoolIM.com
Ajax.NET Professional
Meebo
Tutorials
HTML5 Media Support: video and audio tags
Building an AJAX-Based Chat: The Barebones Structure
Step by Step to AJAX
Ajaxed: Ajax for classic ASP
Periodical Ajax Requests Using MooTools 1.2
Ajax with dojango (dojo+django)
Creating Resizeable Buttons in CSS
Implement WebKit CSS transforms in IE
Login using Ajax and PHP
3D Canvas in Opera