SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (36)
  • LINQ (5)
  • Security (2)
  • Silverlight (3)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box

Using Page Methods in ASP.NET AJAX

(Jun 08 2007 - 09:34:13 PM by Timothy Khouri) - [print article]

If you are looking to enhance your web application using AJAX to provide a more fluid user experience, but you don't know where to start, you might want to start here... using code-behind page methods right in your client script.

One of the most powerful features of ASP.NET AJAX is its ability to tie back-end code to the users' browser in the form of JavaScript with the communication all behind the scenes. Although ASP.NET AJAX can interface with web services so well, you may not have the need or even want to create a web service to do some basic functionality; you may just want to use a method in your page class.

This article is going to discuss a 'real world' scenario where you might use ASP.NET AJAX to call methods on your page. The scenario is that of a "contact us" page. Most contact us pages follow a similar format: 1) display a form for the user to fill out, 2) validate that form against whatever requirements you might have and 3) display a "thank you" message to the user letting them know that you have received the message.

Ah, The Dilemma

There are some annoying problems that come up with implementing this functionality though. One of the most annoying issues is if the user presses "refresh" and accidentally re-posts the inquiry again. So a lot of people will do a redirect when the user posts the form, but that has its own issues. Do you make another page just to say 'thank you'? Do you redirect to the same page with a query string parameter? Why are we posting the entire page and reloading all the HTML, CSS, images etc. just to provide a little functionality?

Those are all good questions, and the answer is: just don't do it. With ASP.NET AJAX you can eliminate all of those bad flaws of the web and provide even faster and snappier experience for the user. Here's how it's done:

Our "Contact Us" Form In ASP.NET

<form runat="server">
   <asp:ScriptManager ID="ScriptManager" runat="server"
       EnablePageMethods="true" />
   <fieldset id="ContactFieldset">
       <label>
           Your Name
           <input type="text" id="NameTextBox" /></label>
       <label>
           Email Address
           <input type="text" id="EmailTextBox" /></label>
       <label>
           Your Message
           <textarea id="MessageTextBox"></textarea></label>
       <button onclick="SendForm();">
           Send</button>
   </fieldset>
</form>

With a little bit of styling, the above markup would look like this:

"Contact Us" form using ASP.NET AJAX

As was discussed in a previous article, you could create a web service that would take the user's input and send the email out. But really, it would be a bit of overkill in this scenario seeing as the functionality needed is specific to this page alone. So what we are going to do is create a method on our page and then tell ASP.NET that this function should be accessible to our AJAX code.

Our Page Method Exposed to ASP.NET AJAX

using System;
using System.Web.Services;

public partial class ContactUs : System.Web.UI.Page
{
   [WebMethod]
   public static void SendForm(string name, string email, string message)
   {
       if (string.IsNullOrEmpty(name))
       {
           throw new Exception("You must supply a name.");
       }

       if (string.IsNullOrEmpty(email))
       {
           throw new Exception("You must supply an email address.");
       }

       if (string.IsNullOrEmpty(message))
       {
           throw new Exception("Please provide a message to send.");
       }

       // If we get this far we know that they entered enough data, so

       // here is where you would send the email or whatever you wanted

       // to do :)

   }
}

Normally I wouldn't include the entire C# code for the page, but I wanted to do it this time to prove a point. There is very little code needed to get this working. Notice I've only needed to include the System.Web.Services namespace, and that was only to get the WebMethod attribute on my method that I want to expose to AJAX. You might want to also note that the method has to be public and static (or "Shared" in VB.NET).

You might also be wondering why I chose to throw an exception if the user didn't supply some data. That's because ASP.NET AJAX will serialize even my exceptions and report them back to me. This is how I'm going to handle my validation and error trapping. Those errors would look something like this:

"Contact Us" showing errors from ASP.NET AJAX

Now lets look at the JavaScript code that is going to bring this all together. Make sure you notice that I'm going to call the function "PageMethods.SendForm". That code is automatically built by ASP.NET when we added that "WebMethod" attribute to our public static method in our code-behind. Here is the JavaScript code:

The Little JavaScript That Could

function SendForm() {
   var name = $get("NameTextBox").value;
   var email = $get("EmailTextBox").value;
   var message = $get("MessageTextBox").value;

   PageMethods.SendForm(name, email, message,
       OnSucceeded, OnFailed);
}

function OnSucceeded() {
   // Dispaly "thank you."

   $get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}

function OnFailed(error) {
   // Alert user to the error.

   alert(error.get_message());
}

So as you would imagine, if the user entered data in all three fields, they would see this when they click the 'Send' button:

"Thank you" message displayed after submitting a form with AJAX

I hope this article has inspired you to look into how you can "mash up" your site with ASP.NET AJAX. It's really easy to use, and Microsoft provides a lot of the functionality for you already.

In the next ASP.NET AJAX article, we are going to see how you can tap into the Membership / Profile API directly in ASP.NET AJAX.

  • Jul 30 2008 - 07:02:40 PM naiplehb

    Wow this is a great example for beginners, easy to understand both logic and objective of the article. I rate this 9. Keep up!!

  • Dec 29 2008 - 02:15:17 AM kapildwt

    this method return authentication failed. you have any idea about that why it is giving error.

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

People to Follow

Experts in the categories related to this article.

  • Jonathan Carter

Related Blogs

These are the most recent blog posts related to this article.

  • Follow up to Self Sorting GridView
  • A Change to the MVC "ActionSelectionAttribute"?
  • How to Handle "Side Content" in ASP.NET MVC
  • LINQ to SQL - Am I Hitting The Database?
  • ASP.NET MVC - Issue with CSS Class Name on ActionLinks

Related Ads

SingingEels.com as of Jul 04 2009 - 04:57:32 AM - (0.0625124)