Asp Focus on input jumping bug - asp.net

I've got a web form using asp.net. In this form I have a lot of inputs.
For one of the drop downs whenever you press it, the focus jumps to the next text box.
This is in a update panel, because there is some server side work required for filtering, hiding, etc.
If the User chooses Australia from visaType_filter then it hides visaType_dd and shows visaType_tb. If they choose NZ its the other way around.
Now my question:
Is there a bug or something that makes focus jump off of a drop down when you click on it to go to the next input (or control)?
Code:
<fieldset>
<asp:UpdatePanel ID="visaTypeUpdatePanel" runat="server">
<ContentTemplate>
<label>Visa Type Number</label>
<label>
<asp:DropDownList ID="visaType_filter" runat="server" Width="40%" OnSelectedIndexChanged="visaType_filter_SelectedIndexChanged" AutoPostBack="true"/>
<asp:TextBox ID="visaType_tb" runat="server" Width="40%" OnTextChanged="visaType_tb_blur" AutoPostBack="true"/>
<asp:DropDownList ID="visaType_dd" runat="server" Width="40%"/>
<asp:Literal ID="visaType_literal" runat="server" />
</label>
</ContentTemplate>
</asp:UpdatePanel>
</fieldset>
<fieldset>

I resolved my problem by using jQuery and Ajax in place of UpdatePanels.

AFAIK, when UpdatePanel gets triggered, the focus does not get maintained. So ideally, you shouldn't be getting any focus at all.
Regardless of reason, you can work-around the issue using ScriptManager.SetFocus method to maintain focus on the drop-down.
You can also have client side solutions for maintaining focus - they essentially work by hooking into AJAX requests to remember the focused control before update panel is triggered and then restoring it back when update panel post-back is completed: see this link for one such solution.

Related

No KeyDown event on my VB.NET Webform

I'm new to VB.NET webform development, but an old VB/Access developer.
I've used Keydown, Keypress events before in my normal development but cannot find this event with this new web development project I'm starting.
I'm assuming it's something to do with the fact it's a web-form. However when I search I can't find others with this issue so thought I'd ask it here. Below is a screen-shot of the events I have on the text control on the web-form where I'm trying to put the keypress event.
(I wanted to attach my picture showing you the events in the list but I don't have 10 reputation points so won't let me include it).
Is this event not available for web-form development? Essentially what I want to do is have the page check that there is text is both the txtUsername and txtPassword controls before enabling the "Log In" command button.
All I have in the drop-down list for the control is:
(Declarations)
DataBinding
Disposed
Init
Load
PreRender
TextChanged
Unload
Consider using a RequiredFieldValidator:
<asp:TextBox id="Foo" runat="server"/>
<asp:RequiredFieldValidator id="Bar"
ControlToValidate="Foo"
Display="Static"
ErrorMessage="*"
runat="server"/>
And in your submit button's click handler:
If Page.IsValid Then
...
Else
...
End If
You will probably also want to use the HTML5 required attribute:
<asp:TextBox id="Foo" runat="server" required="required" />
You might also consider using aria-required:
<asp:TextBox id="Foo" runat="server" required="required" aria-required="true" />

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

Create a web page as 2 parts

I want to develop a registration form with 2 panels. One panel is personal information and another is address details. In these panels the user fills in all details of personal information and after completion of this, the user clicks on Add Address Details. If the user clicks on that, the second panel should be visible without page refresh. How can I accomplish this?
you would use javascript to append the append the second form to to the div of the first form. Or however you have it setup. So in jquery it would look something like this:
<script type="text/javascript">
$('#buttonid').click(function() {
$('#divid').append("<form><input />etc etc etc</form>");
});
</script>
You should use the ASP.NET Wizard control. It is the perfect tool for these scenarios. Scott Gu has a post with some links explaining how to use it. I recommend you look at it.There's a video linked that walks you through a full example.
I don't know, but hiding/showing panels based on certain conditions on the same page feels inelegant and hacky to me.
You should look into using an UpdatePanel. Within there you could place to Panels with different form information. Tie in a few button clicks and hide/show the different panels.
Edit with a simple example
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="upnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Panel ID="pnl1" runat="server">
<!--personal info-->
<asp:Button ID="btn1" runat="server" Text="this button could validate personal info, hide pnl1 and show pnl2" />
</asp:Panel>
<asp:Panel ID="pn2" runat="server" Visible="false">
<!--address info-->
<asp:Button id="btn2" runat="server" Text="this button could validate address information and finally submit the form." />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>

IE 8 - ASP.NET form not submitting when user presses enter key

I have a simple form written in asp.net/C# and when trying to hit enter while in the form's input box doesn't submit the form for some reason. I had implemented a fix for a previous bug where pressing enter would merely refresh the page without submitting the form data but now pressing enter just does nothing, the fix is below:
<div style="display: none">
<input type="text" name="hiddenText" />
</div>
anybody know about a fix for this or a workaround?
I'm assuming you have a button somewhere on your page, as well as an event handler for it.
Have you tried wrapping your form (with the button) inside a Panel control and setting the default button attribute?
i.e.
<asp:Panel id="pnlMyForm" runat="server" DefaultButton="btnMyButton">
<asp:textbox id="txtInput" runat="server" />
<asp:Button id="btnMyButton" text="Submit" runat="server" />
</asp:Panel>
You can specify a default button for a form, which means hitting enter on any input control will fire that button (i.e. target the submit button). I haven't heard of this not working in any specific browser. This should eliminate your need for a workaround/hack.
<form id="form1" runat="server">
<asp:Panel ID="pnlFormContents" runat="server" DefaultButton="btnSubmit">
<!-- add some input controls as needed -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
</asp:Panel>
</form>
Hope this helps...
I don't remember the specifics of the rules, but most browsers have the capability of submitting forms when ENTER is pressed if conditions are met. I think it had to do with whether you had 1 or more-than-one field, or whether or not there was at least one submit button (even if you hide it). I've done it in a site I recently did, but I don't have the code handy, but I can tell you it works without any special scripting. Check this posting for more details:
http://manfred.dschini.org/2007/09/20/submit-form-on-enter-key/

queue asp.net UpdatePanel postbacks

is there a way to queue postbacks with UpdatePanel?
I have a form with many textboxes. each textbox is wrapped inside it's own UpdatePanel with AutoPostBack set to true. so, when textbox changes, postback occurs.
viewstate is disabled (so do not need to worry about it).
the problem appears when user changes one text box and then quickly tabs to the next text box, changes it, and tabs again. some of the postbacks are getting lost and I want to avoid that.
You can get a client-side "hook" when the update panel is about to fire. This means that you could, at least, temporarily disable the text boxes (or have some sort of 'please wait' notification) while the update panel is refreshing.
The following snippet of ASP.NET/Javascript shows how to intercept the update panels firing and disable the textboxes.
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server" ID="updatePane1">
<ContentTemplate>
<asp:TextBox runat="server" ID="textBox1" AutoPostBack="true" OnTextChanged="textBox_TextChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:UpdatePanel runat="server" ID="updatePane2">
<ContentTemplate>
<asp:TextBox runat="server" ID="textBox2" AutoPostBack="true" OnTextChanged="textBox_TextChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</form>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
function InitializeRequest(sender, args) {
if (args._postBackElement.id == 'textBox1' || args._postBackElement.id == 'textBox2') {
document.getElementById('textBox1').disabled = true;
document.getElementById('textBox2').disabled = true;
}
}
</script>
I know this isn't exactly what you originally asked for ("is there a way to queue postbacks with UpdatePanel"), but the net effect is that it forces the user to queue up their requests so no more than one is being processed at a time. You can probably amend this to something more elegant too.
There's no built in way to control this. jQuery has some pretty nifty stuff that makes AJAX calls pretty simple. You might try looking into handling your own postbacks that way.
I know, this is not a answer to your question. But I would recommend a re-think, if you really need to wrap each text box with an update panel. Update panels are useful but you need to be careful in their usage. An plain jQuery Ajax solution may be better in your scenario.

Resources