So sometimes the hardest part of doing any development task is just getting a few configuration lines setup and then you can delve in and get the tasks accomplished. The same is true with AJAX. AJAX is a nice way of interacting with the server without doing a full roundtrip to the server. It allows you to do partial rendering of a portion of a page and opens the door for many slick effects in the process.So, in order to setup the interaction to a web services file in .NET there are a few steps you need to take:
- Create a Web Services File and modify it for asynchronous callbacks
Sounds easy right, well it is but if you don’t know what you are doing it can be a headache so hopefully this will save somebody a ton of time.
- Open Visual Studio and Your Web Project
- Right click on your Project in Solution Explorer and Select “Add New Item”
- Select “Web Service” and name it MyWebService.asmx
- Click Add
- You will notice that there is a default method called HelloWorld() that returns the value “Hello World”
- Uncomment the Line that says
‘ <System.Web.Script.Services.ScriptService()> _
Now we need to prepare the page that will do the asynchronous callback.
- Open the page you want to make asynchronous
- Within the <form> tag you need to add a script manager to the page the code should look like this….
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”> <Services> <asp:ServiceReference Path=”~/MyWebService.asmx” /> </Services></asp:ScriptManager>* If when you created your Web Service file you made it an INLINE SCRIPT meaning it does not have separate code behind file then it would be <asp:ServiceReference InlineScript=”true” Path=”~/MyWebService.asmx” />
Now let’s create a button to call the asynch script and something to show the partial rendering.Add this code in the body of your page inside the <div> tags that are there.
<span id=”MyOutputSpan”></span><br /> <input type=”button” id=”btnGetAsynch” value=”Get Asynch” onclick=”GetAsynch()” />