AJAX.Net - UpdatePanel doesn't delete old content - asp.net

I'm using AJAX.Net (3.5) inside a usercontrol.
The usercontrol contains an UpdatePanel, and inside the UpdatePanelthere is a MultiView.
The ScriptManager is included in the page that act as container for the usercontrol.
To switch between views the usercontrol contains a simple button.
When I click it, the View is changed so the old content is hidden and new content is displayed.
My problem is that the content isn't hidden at all.
The view changes and the new content is displayed, but the old one remains on the page.
To isolate the problem, I tried changing the multiview and switching visibility of a simple label, but the behavior is the same.
Any ideas?

oh I understand. It's all right then. The problem is not of Ajax here. It's just you cannot embed something in <table> tags. In this case, you can try something different than the <table> control. Maybe a <div> or something else. I don't know exactly what sort of situation you have. Maybe you explain the result you want to achieve so I can give you some advice.
Regards

It seems that AJAX.Net doesn't work very well if you have part of a table outside the UpdatePanel.
On my control I want to show or hide some rows of a table. I included only the tr and td tags inside the updatepanel.
To reproduce the problem:
<table>
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<tr>
<td>
<asp:Label ID="lblToShow" runat="server" Text="Label to show" Visible="false" />
<br />
<asp:Label ID="lblToHide" runat="server" Text="Label to hide" />
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
</table>
If you change the visibility using:
lblToShow.Visible = true;
lblToHide.Visible = false;
The text of both labels are shown on the page (lblToHide does not hide)
If you move the table tags inside the UpdatePanel everything works fine.

call
updatepanel.Update()
after you make the changes to your updatepanel
or try
updatepanel.Controls.Clear();

Related

Nested UpdatePanel causes parent to postback?

I'm under the impression that a control in a nested UpdatePanel will cause the top level UpdatePanel to refresh (thus refreshing both UpdatePanels) because any events on that control act as an "implicit" trigger. Is that correct?
I've been trying to wire something like this up-
UserControl
Parent UpdatePanel
"Show" button
ASP:Panel
Dynamically added UserControls, each with UpdatePanels
When the Show button is clicked, the ASP:Panel becomes visible and starts adding UserControls to itself dynamically, based on some back-end logic.
Each of the dynamically added controls (henceforth: UserControls) have their own Atlas-enabled buttons and links, so they have UpdatePanels too. Currently when I click on a link in one of the UserControls, the entire contents of the ASP:Panel disappear, as if it's being re-rendered. All of my dynamically-added controls disappear, and none of their click events are caught in the debugger.
I'm assuming what's happening here is that controls that reside in nested update panels are causing the parent UpdatePanel to post back because they're firing "implicit" triggers. Is there a way for my UserControls to operate autonomously and not mess with the ASP:Panel that contains them?
If not, what strategy should I be pursuing here? If I have to re-render the entire ASP:Panel every time an event happens on one of the (possibly many) UserControls, that means I'll have to recreate the UserControls, which take a bit of effort to create. I'll also have to preserve some kind of view state to recreate them. I'm somewhat new to ASP.NET and that sounds intimidating. I'd rather never refresh the top leve UserControl and ASP:Panel if I can avoid it, and let each of the dynamically-added UserControls fire and handle their own events asynchronously.
EDIT: Instead of adding the controls dynamically, I added them to the markup(not a bad solution). So got rid of the controls disappearing problem, because now the controls are not added dynamically but instead exist in the markup. But still the parent UpdatePanel posting is a big performance hit, because all the UserControls are getting posted instead of one. How do I make only one UserControl postback? Also, I would like to know how to get rid of the problem of controls disappearing if added dynamically?
First off, keep in mind: UpdatePanels do not alter the lifecycle of a page.
All of the Control Tree (including the UpdatePanels) must be reconstructed just as with a Normal Postback Life-cycle.1 2 The UpdatePanels ensure that only a portion of the rendered (HTML) view is returned. Removing all UpdatePanels should result in the same behavior, except with a full postback. For instance, only the HTML representing a nested UpdatePanel (presumably because data changed) might be sent back in the XHR response.
To get "true" AJAX consider Page Methods. Alternatively, DevExpress (and perhaps Telerik and others?) offer their own form of "Callback Panels", which are similar to UpdatePanels, but can bypass parts of the life-cycle (and, as a result often do not support the ViewState model entirely or may introduce their own quirks).
While not understanding the above is the most likely reason for the controls "disappearing", here is my rule: Do Not Let [Nested] UpdatePanels Work "Automatically".
Edge cases with dynamic controls and nested UpdatePanels will be encountered. There might be a nice way to handle this, but I have failed on multiple different attempts.
Instead, for every update panel, run with:
UpdateMode="Conditional"
ChildrenAsTriggers="False"
With the "Conditional" UpdateMode, make sure to manually specify the Trigger control or call panel.Update() (although this hard-wires the Control) as required. Depending on needs ChildrenAsTriggers="True" might work as well. The big thing is that UpdateMode is not "Always" which is the default.
After switching to this approach, I have no problem -- well, almost none -- with nested UpdatePanels.
Happy coding!
1 If the page doesn't render correctly where Partial Rendering (in the ScriptManager) is disabled (e.g. all requests are full postbacks) then there is no reason to expect/believe it will work correctly with UpdatePanels.
2 There are times when it's warranted to "cheat" expensive recomputations in the control tree for controls that will not be re-rendered. However, I would consider these advanced cases that should only be done when performance analysis indicates there is a specific need.
I had a similar issue with a heavy ajax Gridview control, and a HTML page with multiple UpdatePanels, some nested, some not.
It took me over 3 weeks of trial and error, reading, testing, debugging and prototyping to finally resolve all the post backs and partial postbacks.
However I did notice a pattern, which worked for me.
Like the #user above's response, make sure your UpdatePanels are set Conditional and only specificy asp:PostBackTrigger on the final or decisive control that you want the page to do a full postback on. I always use asp:AsyncPostBackTrigger where ever possible.
So for example, if you're using UpdatePanels inside a GridView and you want a popup inside a cell of the gridview's row, then you need to use a nested UpdatePanel.
ie
<asp:TemplateField HeaderText="Actions & Communications">
<ItemTemplate>
<asp:UpdatePanel ID="upAction1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnActionOK" />
</Triggers>
<ContentTemplate>
...
...
<ajaxToolkit:ModalPopupExtender ID="ajaxMPE" runat="server"
BackgroundCssClass="modalBackground"
PopupControlID="upAction2"
TargetControlID="btnADDaction">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upAction2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlACTION" runat="server" CssClass="pnlACTION">
<div id="divHDR">
<asp:Label ID="lblActionHdr" runat="server">** header **</asp:Label>
</div>
<div id="divBOD">
<table style="width: 98%; text-align:left">
<tr>
<td colspan="2">
Please enter action item:<br />
<asp:TextBox ID="txtAction" runat="server" ValidationGroup="vgAction" TextMode="MultiLine" Rows="3" Width="98%"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAction" runat="server" ControlToValidate="txtAction" ValidationGroup="vgAction"
ErrorMessage="* Required" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td colspan="2">
Select staff assigned to this task:<br />
<asp:DropDownList ID="ddlActionStaff" runat="server" AppendDataBoundItems="true" ValidationGroup="vgAction" />
<asp:RequiredFieldValidator ID="rfvStaff" runat="server" ControlToValidate="ddlActionStaff" InitialValue="0" ValidationGroup="vgAction"
ErrorMessage="* Required" SetFocusOnError="True" Width="98%"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<asp:Button ID="btnActionOK" runat="server" Text="OK" OnClick="btnActionOK_Click" ValidationGroup="vgAction" CausesValidation="false" />
<asp:Button ID="btnActionCANCEL" runat="server" Text="CANCEL" OnClick="btnActionCANCEL_Click" ValidationGroup="vgAction" CausesValidation="false" />
</td>
</tr>
</table>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:SqlDataSource ID="sdsTETactions" runat="server" ConnectionString="<%$ ConnectionStrings:ATCNTV1ConnectionString %>"
...
...
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Notice a few things here:
The ModalPopupExtender does not refer to the Ok and Cancel buttons. This is because I want them to trigger a partial postback to the server (code-behind)
The nested UpdatePanel (upAction2) is purely to force a partial postback on that panel only (pnlAction)! Therefore this forces the data validation triggers to work and keep the panel open if the user does not provide data in the requiredfield validators
The main UpdatePanel (upAction1) controls the entire lot and keeps all postbacks held within that panel only and NOT affecting the gridview (not shown entirely).
There is a great article here, which explains it better.
I hope this helps someone

When radio button selection changes do not cause refresh?

When the selection of the radio buttons change I would like to show/hide the panel in the next table cell. I have it hiding and showing fine but each time it causes the page to refresh to the top. Is their a way to stop that refresh? I would like to hide and show the panel dynamically.
<table>
<tr>
<td>
<asp:RadioButtonList runat="server" ID="rblPlayerStatus" AutoPostBack="true" >
<asp:ListItem>Free Agent</asp:ListItem>
<asp:ListItem>I have teammate</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:Panel runat="server" ID="pnlTeamMate">
<asp:Label runat="server" ID="lblTeamMate" Text="Choose Teammate" />
</asp:Panel>
</td>
</tr>
</table>
Use the AJAX.ASP.Net library - then you add a ScriptManager item, and an UpdatePanel. Anything within the UpdatePanel will update through AJAX, not a full page refresh.
Do you have any server side logic based on which show and hide the panel. If yes then you could use update panel control. If it is just client side logic such as
If Free Agent is select show FreeAgent Panel else Team Panel
use javascript or rather jquery to achieve the same.
From your code, I can't see where you hide and show the panel. You could use an updatepanel, but that is best used when you need to retrieve more information from the server.
If you simply want to show and hide the panel, you can do it better with Javascript, by adding some code to the OnClick event to set the panel's visibility css attribute. There are a few tutorials on google about how to do this. Something like this should be sufficient to get you started.
Solution would be either using AJAX (UpdatePanel and ScriptManager) or removing
AutoPostback = true and using JavaScript to display/hide the panel

ASP.NET Webforms UpdatePanel duplicate contents

I've been handed a huge Webforms project which I'm trying to understand, and I have a problem where an Update Panel is duplicating a lot of its content. The aspx code for the panel is huge, hundreds of lines long, but it basically looks like this simple example, only with lots more asp:TextBox and asp:ListBox.
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div><table><tbody><tr><td>
<label>Search</label><asp:TextBox ID="Search" runat="server" />
<asp:LinkButton runat="server" OnClick="find_Click" >Find</asp:LinkButton>
</td></tr></tbody></table></div>
<div id="a"><table><tbody><tr><td>
<label>Result</label><asp:TextBox ID="Result" runat="server" />
</td></tr></tbody></table></div>
</ContentTemplate>
</asp:UpdatePanel>
and code behind like this.
public void find_Click(Object sender, EventArgs e)
{
Result.Text = "oranges";
}
When you click the LinkButton, I would expect to see in the result the <div id="a"> section, but with the text 'oranges' in the TextBox. What you actually get is <div id="a"> with 'oranges', followed by the original <div id="a"> with the empty TextBox. The worst bit is that it doesn't do it in this simple example, nor even in a page that I created that had all the original asp:TextBox and asp:ListBox but filled with dummy data. Can anyone point me to any good ways of approaching this problem?
Another solution would be to make sure all HTML tags are closed inside the asp:UpdatePanel. In my case, I've got the open header tag placed in the Site.Master file (outside of UpdatePanel control) and the closing header tag inside the UpdatePanel control (on aspx page). Because of that, every time the UpdatePanel postbacks it recreates the closing header tag again causing the content to be duplicated. After I placed the closing tag into Site.Master file, everything worked beautifully.
You might have already tried this, but in the actual problem page, is it possible to remove as many server controls out of the updatepanel and just leave in offending textbox and then see what happens? I'm guessing you'll probably have to comment out alot of .cs/.vb code, which can be a pain.
Also try removing the updatepanel and see what happens.
Some serious refactoring later, it now looks like (a very bloated version of) this.
<div><table><tbody><tr><td>
<label>Search</label><asp:TextBox ID="Search" runat="server" />
<asp:LinkButton runat="server" OnClick="find_Click" >Find</asp:LinkButton>
</td></tr></tbody></table></div>
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div id="a"><table><tbody><tr><td>
<label>Result</label><asp:TextBox ID="Result" runat="server" />
</td></tr></tbody></table></div>
</ContentTemplate>
</asp:UpdatePanel>

ASP:Login <LayoutTemplate> always generates a <table>, how can I make it stop?

I've just started tinkering with the ASP:Login control, and want to edit its appearance. So I did the following:
<asp:login ID="login" runat="server" onauthenticate="Authenticate">
<LayoutTemplate>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
</LayoutTemplate>
</asp:login>
Despite the fact that I have no <table> tag anywhere in the document, once I preview the page and view the source, it very clearly shows a <table> there. Ah! How in the world do I prevent this crazy behavior, or am I forced to use tables for layout instead of CSS?
You can set it not to use tables without third party extensions, just make sure you use the
<LayoutTemplate>
</LayoutTemplate>
For laying out your HTML/form inside the control, then set the attribute on the Login that controls the outer table to false.
RenderOuterTable="false"
That's it, no tables :)
You can use the CSS Friendly control adapter for the login control to change it.
http://www.asp.net/CSSAdapters/Membership/Login.aspx
There's a number of things you can do.
The easiest would be to use the Css Control Adapters toolkit's version of the Login control, although it hasn't been updated in a while and I haven't used it recently, so maybe it's not a great option anymore, I'm not sure.
Otherwise you could try creating your own ITemplate and setting it as the property of the LayoutTemplate for the Login control.
Alternately you could rewrite the generated HTML with an IHttpHandler, or even redo it on the client with something like jQuery dom replacement.

Using Panel or PlaceHolder

What is the difference between <asp:Panel > and <asp:PlaceHolder > in ASP.NET?
When should you use one over the other?
A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.
The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.
The Panel does have outer HTML tags but does have some cool extra properties.
BackImageUrl: Gets/Sets the
background image's URL for the panel
HorizontalAlign: Gets/Sets the
horizontal alignment of the parent's
contents
Wrap: Gets/Sets whether the
panel's content wraps
There is a good article at startvbnet here.
PlaceHolder control
Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in the PlaceHolder control.
Panel control
The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.
The Direction property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.
The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUrl property to display a custom image for the Panel control. Use the ScrollBars property to specify scroll bars for the control.
Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>.
More information at ASP.NET Forums
I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.
This is especially true for Hidenfields and Empty labels.
I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.
As mentioned in other answers, the Panel generates a <div> in HTML, while the PlaceHolder does not. But there are a lot more reasons why you could choose either one.
Why a PlaceHolder?
Since it generates no tag of it's own you can use it safely inside other element that cannot contain a <div>, for example:
<table>
<tr>
<td>Row 1</td>
</tr>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</table>
You can also use a PlaceHolder to control the Visibility of a group of Controls without wrapping it in a <div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:PlaceHolder>
Why a Panel
It generates it's own <div> and can also be used to wrap a group of Contols. But a Panel has a lot more properties that can be useful to format it's content:
<asp:Panel ID="Panel1" runat="server" Font-Bold="true"
BackColor="Green" ForeColor="Red" Width="200"
Height="200" BorderColor="Black" BorderStyle="Dotted">
Red text on a green background with a black dotted border.
</asp:Panel>
But the most useful feature is the DefaultButton property. When the ID matches a Button in the Panel it will trigger a Form Post with Validation when enter is pressed inside a TextBox. Now a user can submit the Form without pressing the Button.
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Input is required" ValidationGroup="myValGroup"
Display="Dynamic" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myValGroup" />
</asp:Panel>
Try the above snippet by pressing enter inside TextBox1

Resources