I was recently working on an administrative page for Central Administration, and had the need to use an AudienceEditor control in a form, and more difficult yet, use it inside an AJAX UpdatePanel. The AudienceEditor is the control that is used to enable a user to pick audiences, such as on the Target Audience field in the Advanced section of a Web Part’s Tool Pane.
As the picture shows, this form has a TreeView on the left, and a Panel on the right, and depending on what node in the TreeView is selected, the panel on the right needs to refresh and reload the audience information into the AudienceEditor control. Setting the value in the AudienceEditor via C# is easy, just set the .Text property. Everything works fine when you are setting this value once (e.g. PageLoad), but if you have to set this value on subsequent postbacks, you’ll find that the control keeps the first submitted value, and displays that same value after every postback. You’ll also find that if you use this control in an UpdatePanel, and the control isn’t Visible on initial page load, then the control will not work.
To make this work, first thing is make sure the control is not in a Panel or PlaceHolder that is not visible on initial PageLoad (Visible=false). If you need to hide the control in the beginning, then use CSS display:none, and toggle visibility between PostBacks by Toggling the CssClass of the container control.
Next, the control emits several hidden fields, divs, textareas, and javascript variables into the page. If you want the control to display a new value after postback, you’ll have to clear out these elements on the client side just before postback. This will reset the control, and enable it to take a new value and display that new value after the postback.
Following is the function I wrote to clear out the AudienceEditor. Call this on an OnClientClick event of a button or some similar hook on the control that will be initiating the postback (in my case it was the onNodeClicking client-side event of the Telerik RadTreeView control).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function clearAudienceEditor() { if (typeof(currentEntityEditorXml) != "undefined") { currentEntityEditorXml = ''; } var downLevelTextBox = document.getElementById('<%= audienceEditor.ClientID + "_downLevelTextBox" %>'); var upLevelDiv = document.getElementById('<%= audienceEditor.ClientID + "_upLevelDiv" %>'); var hiddenSpanData = document.getElementById('<%= audienceEditor.ClientID + "_hiddenSpanData" %>'); if (downLevelTextBox != null) { downLevelTextBox.value = ''; } if (upLevelDiv != null) { upLevelDiv.innerHTML = ''; } if (hiddenSpanData != null) { hiddenSpanData.value = "&#160;"; } } |