ASP.NET AJAX using JSON – Here’s how.

image Last week I wrote a post about how simple JSON is. In it I explained the main differences between using JSON and using the update panel. I really started out thinking I’d get to how to write JSON code, but I ran out of space. Well, today, we get to the HOW.

All JSON really is, is the ability to have JavaScript code call a WebService for our data, and write it into the HTML on the client side. If you know anything about how to write a WebService, this should be rather trivial because your web service is going to look just like any other web service with the exception of an added attribute.

To make a WebService accessible to JSON, add the following Attribute to your WebService class:

[ScriptService]

You will probably also need to add

using System.Web.Script.Services;

to the top of your page.

Now, any WebMethod in your WebService can be called by your JavaScript on the client side.

As with any AJAX code in ASP.NET, you’ll need to add a ScriptManager to your page. But, in addition, you’ll also need to add a Services section in your ScriptManager to tell the ASP.NET page to pull in the javascript that the WebService code will now produce for you. You should have this code at the top of the FORM section of your HTML.

      <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
          <asp:ServiceReference path="~/WebService.asmx" />
        </Services>
      </asp:ScriptManager>

Where, “~/WebService.asmx” refers to the web service you want to be able to access.

Now in the javascript event handler where you want to be able to call the WebService, you just call the WebService similar to how you would call any other function. In fact, if you write this code in the ASPX page, you will even get intellisense.

So, assuming we have a class named “WebService” with a function called “HelloWorld” that returns a string, our calling code will look like:

WebService.HelloWorld(Success,Fail,null);

Note that our call takes three parameters, even though our function in the WebService does not take any parameters.

The first parameter is a pointer to a JavaScript function to call if the call to the WebService succeeds. The second is a pointer to the JavaScript function to call if the WebService call fails, and the third parameter is a JavaScript context object to pass to the Success function. Since I don’t have any data I need to pass along, I just pass in NULL in the code above.

If the WebService method takes parameters, the parameters are listed before the success, fail, and context parameters.

If the WebService call fails, the JavaScript function that we specified for fail will be called. It needs to accept one parameter which will have the error message in it. You can use this to display an error message in an alert box.

When the WebService returns successfully, the Success function will be called. This function takes two parameters. The first is the return value. The second is the context object we passed when we originally called the WebMethod. You can then use standard JavaScript to find an HTML element on the page to put the new content into:

function Success(result,context)
{
document.getElementById("fillMeAtLoadTime").innerHTML = result;
}

And that’s really all there is to JSON. The rest is really just a matter of imagination and JavaScript.

Other places talking about JSON:

  • Dynamically create ASP.NET user control using JQuery and JSON …- Dynamically create ASP.NET user control using JQuery and JSON enabled Ajax Web Service Please read my previous post Dynamically create ASP.NET user control using ASP.NET Ajax and Web Service to understand this approach. …
  • ASP.NET, Web Services and Json- Implementing Json web services in ASP.NET is very easy:. – open Visual Web Developer 2008 Express Edition – create a new ASP.NET project – create a “Service” directory – inside “Service” create an “AJAX-enabled WCF Service” file named …
  • Extending an existing ASP.NET Web Service to support JSON- Describes how to use JSON serialization functionality in .NET 3.5 to add JSON support to a standard ASP.NET Web Service. Download Mp3 Songs for Free.

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • Using JSON in ASP.NETUsing JSON in ASP.NET If you've been avoiding using JSON in your ASP.NET application because you think it's hard, you're an idiot. I can say that, because I've been avoiding it for exactly that reason. I've […]
  • ASP.NET JSON  and ViewStateASP.NET JSON and ViewState I received the following question recently about my article "ASP.NET AJAX using JSON - Here’s how." If we update the value of a textbox or label via a JSON web service call - will the […]
  • jQuery, JSON, and ASP.NETjQuery, JSON, and ASP.NET A few months ago, I demonstrated how to use ASP.NET's JSON capabilities.  Lately, I've been demonstrating how to use jQuery.  Both use a considerable amount of JavaScript so if there is […]
  • Mixing ASP.NET, jQuery and JSONMixing ASP.NET, jQuery and JSON I received the following question last week: I am building a web application... I have a form with asp.net server control textbox and dropdownlist... how can I send this to the […]
  • Who’s AJAX Should You Use?Who’s AJAX Should You Use? Just had someone ask me a question this morning that I bet many others have asked or are asking... Should I use MS-AJAX, that comes with ASP.NET or should I use something from another […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

2 Pingbacks/Trackbacks

  • Pingback: Dew Drop - August 4, 2008 | Alvin Ashcraft's Morning Dew

  • pep

    I saw a full in depth article on this at dotnettutorials.com.

  • Jigar

    This approach requires us to have a aspx page on client side(from where the web service is called). Is there a way in which a plain html page or any other page can call json webservice from javascript?

  • Dave

    There is no clean way that I know of. I guess you could write it using ASPX and then copy and paste the result to HTML. But, it would be just as easy to implement caching on your ASPX page which would also give you better performance.

    Why is HTML a requirement?

  • Pingback: jQuery, JSON, and ASP.NET

  • Luke

    If we update the value of a textbox or label via a JSON web service call – will the value of that textbox/label be written to the viewstate or whatever so that the server side code can see the new values that came from the JSON request?

  • Dave

    Luke,

    See my article from this morning, http://blog.dmbcllc.com/2009/01/26/aspnet-json-and-viewstate/ for the complete answer to your question.

  • Will

    @jigar,

    You can create an aspx page and send the json via the Response object.

    In your Page_Load() event:

    Response.Write( jsonString ); // string containing the json response
    Response.End(); // Sends json string to the client, ends the response to avoid trailing asp.net html
    Response.Close();

  • Dave

    @Will,

    He wants to remove the need for ASPX. Why would you emit json via aspx when you could do it with asmx? That’s just silly.

    What he COULD do is use jQuery instead of ASPX which I’ve also covered on this site.

  • Will

    @Dave,

    He wants to access the json from a non-aspx page; he doesn’t say anything about the json source (though context would indicate that it would be from a Microsoft technology). That is, he can’t use the AJAX.NET script manager because he’s not using ASP.NET generated pages on the client side. I assumed he was using jQuery or some other 3rd-party AJAX framework.

    If you’re only using json, why use asmx when there are simpler options? In this situation, asmx and the related framework are more trouble than they’re worth, particularly if you don’t work with them regularly (or in my case, at all).

    Silly if you’re trying to do it the One True Way, but not if your time is worth something.

  • Dave

    Since neither of us know exactly what he was asking, we’ll just have to wait until he tells us.

    I would differ with you re using ASMX or not, especially using it with jQuery.

Awards & Certs


Links