Assuming that you're writing VB.NET. The blogging app won't let me put less than / greater than tags in so make sure you add these.
1. Create a new ASP.NET Web Service Application project in Visual Studio 2008 / 2010. Call it 'JSONWebService'.
2. Rename the default 'Service1.asmx' to 'json.asmx'. Also rename the code behind class from 'Service1' to 'json' and change the binding on the front .asmx page.
3. There should be a commented line in the template code that the project creates that looks like "system.web.script.services.scriptservice()_" . Uncomment this.
4. Add a new Public Class to your code behind. The example I am going to use will provide data on staff contact information (i.e. phone number, email address) but you can fit in whatever data you want. So I will do Public Class StaffInformation. Create four public string variables within the Class; Public forename As String, Public surname As String, Public phonenumber As String, Public email As String.
5. Add a new Web Method to the json Class. Call it GetEmployees so you'll need to do Public Function GetEmployees(ByVal id As String) As List(Of StaffInformation). Make sure you add the WebMethod() line of code above the Function declaration - you can copy / paste that from the HelloWorld method that the project template creates.
6. You'll also need to add this line inside tags below the WebMethod declaration: System.Web.Script.Services.ScriptMethod(UseHttpGet:=False, ResponseFormat:=Script.Services.ResponseFormat.Json)
7. Couple of important points here. The WebMethod is returning a List - that's pretty vital to the JSON output because from what I have read .NET struggles to convert more complicated objects such as DataTables. I had never used this before until I sorted this example out and it's a useful look into how OO works in VB.NET. The ScriptMethod in point 6. is also important because a) it tells the web service to return data in JSON notation, not XML and b) it forces the AJAX call to get made using HTTP POST and not GET. POST is essential when you write the AJAX call in jQuery.
8. The GetEmployees function is going to read some data from a database, put it into the List object and then return the List. Something clever then serialises the List into JSON.
9. Create SqlConnection, SqlCommand and SqlDataReader objects and set the first two up. In my example I did a simple SELECT statement against a table to return the four fields I'm looking for (as specified in the custom List).
10. Declare a new instance of the List (i.e. Dim MyList = New List(Of StaffInformation).
11. Execute the SqlDataReader. Loop through the dataset with it and do the following:
12. Dim item = New StaffInformation With {.field1 = reader(0).ToString(), .field2 = reader(1).ToString(), etc.}
13. MyList.Add(item)
14. Return MyList at the end of the Function.
15. You also need to modify the Web.Config file to allow AJAX HTTP calls. Inside the system.Web node add webServices, then protocols inside that, and then two new entries inside protocols: 'add name="HttpGet"' and 'add name="HttpPost"'.
16. That's it. Compile, publish to IIS and test with a jQuery AJAX call.
Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts
Wednesday, 8 September 2010
Friday, 3 September 2010
jQuery with ASP.NET Web Service
Had a very productive day today hooking up an HTML web page with the jQuery library to an ASP.NET web service. I've written previously about my research into this and while the WCF RESTful stuff looked good I wasn't convinced it was the best way forward to this. We've decided to use a sickness absence report as a trial for developing some skills in Javascript development and today I was looking for a better way to expose web service methods that jQuery could easily communicate with.
After several hours of searching and some dead ends I stumbled across this article http://www.dotnetcurry.com/ShowArticle.aspx?ID=320&AspxAutoDetectCookieSupport=1 that finally showed me how to do all the things I have been reading about. The standard ASP.NET web service gets a few additions to it (such as System.Web.Script.Services.ScriptService / ScriptMethod) and you can tell the individual ScriptMethod to return data as JSON. That's great because the numerous jQuery AJAX examples all deal with JSON instead of XML. The article also shows you how to return a List of data from VB.NET (something I had never done before - I have always used DataSet / DataTable) which allows you to create a custom List with a number of attributes and then add as many items to this List as you like. The list gets populated with data from the SQL result set.
You can then write what is now becoming a pretty standard jQuery AJAX function, get a result set object, loop through it with a FOR loop and write the output into an HTML table, which then gets displayed in a div on the page (that's another thing I love about jQuery; you can actually modify whole divs).
There are plenty of examples in C# on the web but this is the first complete working example I found in VB.NET. Check it out!
After several hours of searching and some dead ends I stumbled across this article http://www.dotnetcurry.com/ShowArticle.aspx?ID=320&AspxAutoDetectCookieSupport=1 that finally showed me how to do all the things I have been reading about. The standard ASP.NET web service gets a few additions to it (such as System.Web.Script.Services.ScriptService / ScriptMethod) and you can tell the individual ScriptMethod to return data as JSON. That's great because the numerous jQuery AJAX examples all deal with JSON instead of XML. The article also shows you how to return a List of data from VB.NET (something I had never done before - I have always used DataSet / DataTable) which allows you to create a custom List with a number of attributes and then add as many items to this List as you like. The list gets populated with data from the SQL result set.
You can then write what is now becoming a pretty standard jQuery AJAX function, get a result set object, loop through it with a FOR loop and write the output into an HTML table, which then gets displayed in a div on the page (that's another thing I love about jQuery; you can actually modify whole divs).
There are plenty of examples in C# on the web but this is the first complete working example I found in VB.NET. Check it out!
Tuesday, 31 August 2010
More ASP.NET AJAX UpdatePanel excitement
I gave up. The UpdatePanel wasn't really designed to do what I want it to do. I thought initially that I could get nested UpdatePanels to just refresh localised content; i.e. if I created one inside a div then by setting it to conditional update I could just make it refresh the controls inside the div. This is not the case - event nested panels refresh everything.
The Conditional update flag is OK but you can't make a control that's outside the panel refresh it. And having a timer that refreshes content is a no - no for the reason discussed above; every ten seconds everything gets refreshed which means the text box you are typing into loses focus and the modal popup with a list of options pops down again.
I have a series of scripts that I have embedded into the main .aspx page via .ascx controls. These scripts open a new app hosted on an entirely seperate server in a new IE tab. Once the user has finished with this second app I need a way to refresh the content on the main .aspx page so what I ended up doing was navigating through the control structure of the main page from the .ascx control and finding the labels etc. that I want to update. I rigged up a modal popup with a giant refresh button and when the user jumps out to the second app this modal popup gets popped and it's the first thing the user sees when they close the second app. The refresh button then brings my main page up to date.
Navigating the control structure was a bit of a nightmare; set Me.Parent.Page and then iterate through five layers of controls to find the one I want (and that's just to pick out one label, there's more work to do). But at least I found a viable solution.
The Conditional update flag is OK but you can't make a control that's outside the panel refresh it. And having a timer that refreshes content is a no - no for the reason discussed above; every ten seconds everything gets refreshed which means the text box you are typing into loses focus and the modal popup with a list of options pops down again.
I have a series of scripts that I have embedded into the main .aspx page via .ascx controls. These scripts open a new app hosted on an entirely seperate server in a new IE tab. Once the user has finished with this second app I need a way to refresh the content on the main .aspx page so what I ended up doing was navigating through the control structure of the main page from the .ascx control and finding the labels etc. that I want to update. I rigged up a modal popup with a giant refresh button and when the user jumps out to the second app this modal popup gets popped and it's the first thing the user sees when they close the second app. The refresh button then brings my main page up to date.
Navigating the control structure was a bit of a nightmare; set Me.Parent.Page and then iterate through five layers of controls to find the one I want (and that's just to pick out one label, there's more work to do). But at least I found a viable solution.
Thursday, 26 August 2010
Fun (!) with the ASP.NET AJAX UpdatePanel
Still unlucky enough to be developing with the ASP.NET AJAX UpdatePanel? Me too. You have my condolences. After spending some time getting to grips with it you may be at the stage where you realise that you could use it to make real time updates to areas of your web app by using a Timer to run an automatic refresh.
The problem I found initially was that doing this tended to take over the entire web app and refresh everything. I also ran into problems with Triggers - i.e. I couldn't get certain parts of the app to update because I needed to fire them through an Asycnhronous trigger and it wasn't working.
So this afternoon I set out to try and solve the problem. I am working on an app that will 'branch out' to another application on another server in certain circumstances. The user completes some actions in this second app and will then close the IE window / tab and return to my app. When this happens I want some things to change - mainly text and contents of grid views. Should be achievable with the UpdatePanel. Right?
I have set up a web form that inherits from a MasterPage. First thing on the page is the ToolKitScriptManager control, followed by an UpdatePanel called 'upMain' with UpdateMode = Conditional. I have a div with some content, and then underneath this an Accordion control with five different panes.
First thing is a note on the timer. Initially I had a set of labels in the header div (inside on UP) and a grid in the fifth pane (inside a seperate UP) that I wanted to refresh. I tried setting a Timer on each of these and using them as ASync triggers on each UpdatePanel but that didn't work - only the first Trigger would fire for some reason. I tried creating one Timer inside the Main UP and using this as the Trigger for each sub - UP but that didn't work either - it just took over the entire app and started stopping data input half way through, for example (no good for the user experience).
The answer, it turns out, is to create the Timer inside the first sub - UP and wire up the ASync triggers for both sub-UP's to this Timer. That works OK and refreshes both sets of content. To get the second sub-UP to recognise the Timer you have to give it the Unique ID that ASP.NET assigns which is something like ctl00$main$... To get this set a breakpoint on your Timer event handler and check the value of sender when it breaks - you can interrogate the object and find the UniqueID value here.
More on this later.
The problem I found initially was that doing this tended to take over the entire web app and refresh everything. I also ran into problems with Triggers - i.e. I couldn't get certain parts of the app to update because I needed to fire them through an Asycnhronous trigger and it wasn't working.
So this afternoon I set out to try and solve the problem. I am working on an app that will 'branch out' to another application on another server in certain circumstances. The user completes some actions in this second app and will then close the IE window / tab and return to my app. When this happens I want some things to change - mainly text and contents of grid views. Should be achievable with the UpdatePanel. Right?
I have set up a web form that inherits from a MasterPage. First thing on the page is the ToolKitScriptManager control, followed by an UpdatePanel called 'upMain' with UpdateMode = Conditional. I have a div with some content, and then underneath this an Accordion control with five different panes.
First thing is a note on the timer. Initially I had a set of labels in the header div (inside on UP) and a grid in the fifth pane (inside a seperate UP) that I wanted to refresh. I tried setting a Timer on each of these and using them as ASync triggers on each UpdatePanel but that didn't work - only the first Trigger would fire for some reason. I tried creating one Timer inside the Main UP and using this as the Trigger for each sub - UP but that didn't work either - it just took over the entire app and started stopping data input half way through, for example (no good for the user experience).
The answer, it turns out, is to create the Timer inside the first sub - UP and wire up the ASync triggers for both sub-UP's to this Timer. That works OK and refreshes both sets of content. To get the second sub-UP to recognise the Timer you have to give it the Unique ID that ASP.NET assigns which is something like ctl00$main$... To get this set a breakpoint on your Timer event handler and check the value of sender when it breaks - you can interrogate the object and find the UniqueID value here.
Subscribe to:
Posts (Atom)