-
March 29th, 2007, 04:07 PM
#1
Ajax command parsing
Hi,
I am creating a web app with VB.NET 1.1 using AJAX. I was wondering if there is a better way to handle events than what I am doing, without downloading an ajax framework.
My method:
Each button on web form calls javascript that creates an xml fragment and posts it to a class that handles ajax requests for the page.
XML:
Code:
<AjaxRequest>
<Command>Foo</Command>
<Params>
<Param name="param1">Bar</Param>
<Param name="param2">Again</Param>
</Params>
</AjaxRequest>
The code on the server pulls out the command field and runs it through a select case to determine which function to call.
Code:
Imports System.Web
Imports System.Xml
Public Class Ajax
Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return True
End Get
End Property
'Here is where the action is...
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
Dim xmlDoc As XmlDocument
'If the XML document was submitted via post method, then load it in the DOM document
If (context.Request.InputStream.Length > 0 And context.Request.ContentType.ToString().IndexOf("/xml") > 0) Then
xmlDoc = New XmlDocument
xmlDoc.Load(context.Request.InputStream)
Select Case xmlDoc.GetElementsByTagName("Command").Item(0).InnerText
Case "Bar"
Call Bar()
Case "Func2"
Call Func2()
Case "HelloWorld"
Call HelloWorld()
...etc...
End Select
End If
End Sub
Public Sub Bar()
'Get params, do some work, and return something in the Response...
End Sub
End Class
Instead of this select case, are there better methods? It just seems like there should be...
Thanks,
Ranthalion
-
March 29th, 2007, 04:58 PM
#2
Re: Ajax command parsing
Originally Posted by Ranthalion
Instead of this select case, are there better methods? It just seems like there should be...
You could use some kind of map (key/value collection) between a specific string (the command) and a delegate (the function to call). Then instead of the select-case stament you simply grab the command from the xml, then lookup the correspoing delegate in the map, and then call the delegate.
And AFAIK it would be cleaner to use XPath to lookup the command instead of GetElementsByTagName.
- petter
-
April 2nd, 2007, 08:03 AM
#3
Re: Ajax command parsing
Thanks. The map seems like it would be pretty much the same thing as the Select Case implementation. Whenever I add a new function, I would have to manually update the map to contain the new command string and function name. I'll think about it some more, though.
I'm not familiar with XPath yet, so I'll definately check that out. This is the first project that uses xml. Thanks again!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|