views:

2125

answers:

2

What's the best way to implement user controls that require AJAX callbacks?

I want to accomplish a few things:

  • Have events done in the browser (eg, drag and drop) trigger an AJAX notification that can raise a control event, which causes code on the page using the control to do whatever it needs to do (eg, change a value in a database).
  • Have partial updates (NOT using an updatepanel) that can do things like populate an auto-complete dropdown underneath a textbox.
  • Implement a single user control that is generic enough to be reused on several pages
  • Avoid having to implement logic on the page itself that passes events back to the control, because that is repetitive and hard to maintain

I'm using jQuery for most of the client side stuff, but for the actual AJAX calls I don't really care if it's jQuery or the ASP AJAX libraries.

Effectively what would be perfect is PageMethods on the user control, that would be easily callable from client-side script. Unfortunately, as far as I'm aware, pagemethods do not work on user controls.


I'll use an autocomplete control as an example:

I should be able to put the autocomplete control on the page, and then in the page code, have eg:

Public Sub HandleLookup(ByVal input As String, ByRef list As List(Of String) Handles MyControl.LookupEntries
  list = New List(Of String)
  ' Query database for list of items.. 
  For Each item as String in FullItemList
    If item.StartsWith(input) then list.Add(item)
  Next
  Return list
End Sub

And do nothing else .. the rest of the code should be in the usercontrol.


Note, the controls I'm trying to make are much more specific than eg, autocomplete. They do not exist in any 3rd party libraries and I really need to be able to make them myself.

+1  A: 

Look into implementing ICallbackEventHandler in your Page -- it's a simple way to make a call back to a page function from JavaScript.

Here's a good tutorial:

http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119

Lou Franco
Thanks, that got me going. It's not really that intuitive or powerful (really only allows one parameter (string)) - which meant I had to write a little library to encode/decode the string and let me simulate multiple "functions". But it does work, and now everything is self-contained in one control
gregmac
A: 

You might want to check out; Ra-Ajax UserControl Sample and combine that knowledge with Ra-Ajax Drag and Drop

Click the "Show code" C# icon to the left to see the usage of the code...

Thomas Hansen