Common_AddDynamicData_VBNet\PartialPostback_RegisterDataItem.aspx.vb
' Copyright 2010 ESRI ' ' All rights reserved under the copyright laws of the United States ' and applicable international laws, treaties, and conventions. ' ' You may freely redistribute and use this sample code, with or ' without modification, provided you include the original copyright ' notice and use restrictions. ' ' See the use restrictions. ' Imports Microsoft.VisualBasic Imports System Public Partial Class PartialPostback_RegisterDataItem Inherits System.Web.UI.Page #Region "Instance Variable Declarations" Private m_CheckBoxId As String = String.Empty Private Const AGSLocalName As String = "AGSLocalMapResource" Private Const AGSInternetName As String = "AGSInternetMapResource" Private Const IMSName As String = "IMSMapResource" #End Region #Region "ASP.NET Page Event Handlers" Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Dim scriptKeyCustom As String = "customDataItemScript" ' Check whether a script block with the name stored in scriptKeyCustom has already ' been registered on the client, and whether the page is in an asynchronous postback. ' If neither of these is true, create and register the script block. Note that replacing ' ScriptManager1.IsInAsyncPostBack with Page.IsPostback will work initially, but if a ' full page postback occurs, the script may be lost. If (Not Me.Page.ClientScript.IsClientScriptBlockRegistered(Me.GetType(), scriptKeyCustom)) AndAlso (Not ScriptManager1.IsInAsyncPostBack) Then ' Construct the JavaScript block that will be responsible for processing data items. ' ' onLoadFunction specifies AsyncResponseHandler as a handler for the pageLoading AJAX ' client-side event. This event fires during asynchronous postbacks after the response ' has been received from the server, but before any content on the page is updated. ' ' AsyncResponseHandler retrieves the data items registered server-side during the ' asynchronous postback by accessing the dataItems property on the second argument ' passed to the handler. It then gets the particular data item corresponding to the ' page by passing the page's client ID to the dataItems array as an array index. This ' data item, assumed to be formatted as a Web ADF callback result, is then passed to ' ESRI.ADF.System.processCallbackResult - the client-side Web ADF function responsible ' for parsing callback results and updating Web ADF controls accordingly. ' ' Below the function declarations, onLoadFunction is added as a handler for the AJAX ' client-side event init, which is raised once when the page is first rendered. This ' is therefore the appropriate place for onLoadFunction to be called, since the ' asynchronous pageLoading handler in this case can remain unchanged for the life ' of the application. ' ' The functions are enclosed in an extra pair of curly braces to allow the subsequent ' call to String.Format. String.Format is designed to replace the contents of curly ' braces with the parameters passed to the function call. These extra braces "escape" ' the braces that must enclose a JavaScript function's logic, essentially telling ' String.Format to not replace the contents of these particular braces. Dim scriptBlock As String = "" & ControlChars.CrLf & " " & ControlChars.CrLf & " function onLoadFunction(){{" & ControlChars.CrLf & " Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(AsyncResponseHandler);" & ControlChars.CrLf & " }}" & ControlChars.CrLf & ControlChars.CrLf & " function AsyncResponseHandler(sender, args) {{" & ControlChars.CrLf & " var dataItems = args.get_dataItems();" & ControlChars.CrLf & " if (dataItems['{0}'] != null)" & ControlChars.CrLf & " ESRI.ADF.System.processCallbackResult(dataItems['{0}']);" & ControlChars.CrLf & " }}" & ControlChars.CrLf & ControlChars.CrLf & " Sys.Application.add_init(onLoadFunction);" ' Insert the client ID of the page into the script block. scriptBlock = String.Format(scriptBlock, Page.ClientID) ' Register the script on the client. This will make the script block available client-side ' and execute statements that are not function or object declarations, in this case adding ' onLoadFunction as a handler for the init event. Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), scriptKeyCustom, scriptBlock, True) End If End Sub #End Region #Region "ASP.NET Web Control Event Handlers" Public Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) ' Declare the variable to store the callback response Dim callbackResult As String = String.Empty Try ' Get a reference to CheckBoxList1 by casting the sender parameter to CheckBoxList Dim checkBoxList As System.Web.UI.WebControls.CheckBoxList = CType(sender, System.Web.UI.WebControls.CheckBoxList) ' Declare a list object to hold the list of visible map resources Dim visibleResourceList As System.Collections.Generic.List(Of String) ' Check whether the visible resource list exists in the session variables If Session("visibleResources") Is Nothing Then ' The visible resource list isn't among the session variables, so instantiate a ' new list object and assign it to visibleResourceList. visibleResourceList = New System.Collections.Generic.List(Of String)() Else ' Assign the visible resource list session variable to visibleResourceList visibleResourceList = CType(Session("visibleResources"), System.Collections.Generic.List(Of String)) End If ' Iterate through the checkbox list items and add/remove a map resource based ' on which item's selected state disagrees with the visibleResourceList Dim i As Integer = 0 Do While i < checkBoxList.Items.Count ' Get a reference to the current list item Dim listItem As System.Web.UI.WebControls.ListItem = checkBoxList.Items(i) ' Check whether the item's selected property matches whether it is ' contained in the list of visible resources. If the item is selected ' but not in the visible resource list, then the corresponding resource ' needs to be added to the map. If the item is in the visible resource ' list but not selected, then the corresponding resource needs to be ' removed from the map. If listItem.Selected <> visibleResourceList.Contains(listItem.Text) Then Dim resourceName As String = String.Empty ' Assign the resource name variable based on the text of the current list item Select Case listItem.Text Case "ArcGIS Server Local" resourceName = AGSLocalName Case "ArcGIS Server Internet" resourceName = AGSInternetName Case "ArcIMS" resourceName = IMSName End Select ' Call the AddOrRemoveMapResource method, which adds/removes ' resources to/from the map callbackResult = AddOrRemoveMapResource(resourceName, listItem.Selected) ' Modify the list of visible resources so that it is in sync ' with which resources are visible on the map If visibleResourceList.Contains(listItem.Text) Then visibleResourceList.Remove(listItem.Text) Else visibleResourceList.Add(listItem.Text) End If ' The checked item has been found and action taken accordingly, ' so we can exit the loop iterating through the CheckBoxList items Exit Do End If i += 1 Loop ' Update the visible resource list session variable Session("visibleResources") = visibleResourceList Catch exception As System.Exception Dim errorCallbackResult As ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult = ErrorHandling.GetErrorCallback(exception) Map1.CallbackResults.Add(errorCallbackResult) callbackResult = Map1.CallbackResults.ToString() End Try ' Register the callback response as a data item. This sends the response back ' to the client, where it can be accessed by handlers of the pageLoading, pageLoaded, or ' endRequest events on the PageRequestManager object. More specifically, the callback ' response will be inserted into the dataItems array, which is passed to the client as a ' property of the second argument passed to any of the three aforementioned event ' handlers. The response can be retrieved from the array by specifying the client ID of ' the control passed into the RegisterDataItem call (in this case Page) as the array ' index. In this case, a pageLoading handler was declared in the script block ' registered in the Page's PreRender event, and this handler retrieves the dataItem and ' passes it to ESRI.ADF.System.processCallbackResult. ScriptManager1.RegisterDataItem(Page, callbackResult, False) End Sub #End Region #Region "Instance Methods" Private Function AddOrRemoveMapResource(ByVal resourceName As String, ByVal isChecked As Boolean) As String Try Dim mapResourceItemCollection As ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemCollection(Of ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem) = MapResourceManager1.ResourceItems Dim mapResourceItem As ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem = Nothing ' Get current resource item count to determine if the primary map resource needs to be set. Dim mapResourceCount As Integer = mapResourceItemCollection.Count ' If checked, add the resource. If unchecked, remove the resource. If (Not isChecked) Then mapResourceItem = mapResourceItemCollection.Find(resourceName) mapResourceItemCollection.Remove(mapResourceItem) Map1.Refresh() Else mapResourceItem = New ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem() ' Map resource items consist of a definition and display settings. The definition ' will define the data source and resource parameters. Display settings will define ' map image properties and retrieval types. Dim gisResourceItemDefinition As ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemDefinition = New ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemDefinition() ' Check the name of the resource corresponding to the checkbox checked and initialize ' the resource definition accordingly Select Case resourceName Case (AGSLocalName) gisResourceItemDefinition.DataSourceDefinition = "localhost" gisResourceItemDefinition.DataSourceType = "ArcGIS Server Local" gisResourceItemDefinition.ResourceDefinition = "Layers@USA" Case (AGSInternetName) gisResourceItemDefinition.DataSourceDefinition = "http://serverapps.esri.com/arcgis/services/" gisResourceItemDefinition.DataSourceType = "ArcGIS Server Internet" gisResourceItemDefinition.ResourceDefinition = "Layers@SamplesNet/NorthAmerica" Case (IMSName) gisResourceItemDefinition.ResourceDefinition = "states" gisResourceItemDefinition.DataSourceDefinition = "localhost@5300" gisResourceItemDefinition.DataSourceType = "ArcIMS" End Select ' Associate the resource item definition with a map resource item mapResourceItem.Definition = gisResourceItemDefinition ' Set the resource item's name to the passed-in resource name mapResourceItem.Name = resourceName ' Initialize display settings Dim displaySettings As ESRI.ArcGIS.ADF.Web.DisplaySettings = New ESRI.ArcGIS.ADF.Web.DisplaySettings() displaySettings.Transparency = 50.0F displaySettings.Visible = True displaySettings.ImageDescriptor.ImageFormat = ESRI.ArcGIS.ADF.Web.ImageFormat.PNG8 displaySettings.ImageDescriptor.TransparentBackground = True displaySettings.ImageDescriptor.TransparentColor = System.Drawing.Color.White displaySettings.ImageDescriptor.ReturnMimeData = False ' Associate the map resource with the display settings mapResourceItem.DisplaySettings = displaySettings ' Insert the new resource item at the beginning (top). MapResourceManager1.ResourceItems.Insert(0, mapResourceItem) mapResourceItem.InitializeResource() ' Make sure that the resource item initialized properly. Call the ' GetResourceInitFailureCallback error handling method if the resource item ' did not initialize. If mapResourceItem.FailedToInitialize Then Dim exceptionMessage As String = mapResourceItem.InitializationFailure.Message Return ErrorHandling.GetResourceInitFailureCallback(exceptionMessage, m_CheckBoxId) End If End If ' Refresh the Toc and add to Map's callback result collection. Toc1.Refresh() Map1.CallbackResults.CopyFrom(Toc1.CallbackResults) Catch exception As System.Exception Dim errorCallbackResult As ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult = ErrorHandling.GetErrorCallback(exception) Map1.CallbackResults.Add(errorCallbackResult) End Try ' Return the Map's collection of callback results as a string Return Map1.CallbackResults.ToString() End Function #End Region End Class