简体   繁体   中英

How to maintain the focus on same control after asynchronous postback?

I have 3 textboxes , one is in updatepanel it will refresh for every 4 seconds. During refresh the controls which are not in update panel also loosing focus. I want to keep focus on those controls.

Here is my code:

<asp:UpdatePanel ID="upnlChat" runat="server">
    <ContentTemplate >
        <asp:TextBox ID="txtChatBox" ReadOnly="true" TextMode="MultiLine" 
            CssClass="mymultitextboxclass" runat="server"></asp:TextBox>
     </ContentTemplate>
      <Triggers>
      <asp:AsyncPostBackTrigger ControlID="timerChat" />

      </Triggers>
    </asp:UpdatePanel>
    <asp:Timer ID="timerChat" Interval="4000" runat="server" ontick="timerChat_Tick" ></asp:Timer>
        <table>
        <tr><td>User: </td><td colspan="2"><asp:TextBox ID="txtUser" runat="server" ></asp:TextBox><br /></td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredUserName" runat="server" ErrorMessage="Username Required" ControlToValidate="txtUser" ></asp:RequiredFieldValidator> </td></tr>
        <tr><td>Message: </td><td><asp:TextBox ID="txtMsg" CssClass="mymsg" TextMode="MultiLine" onkeydown="if (event.keyCode == 13) { btnSend.focus(); this.form.submit();  }"  runat="server"></asp:TextBox></td>
        <td colspan="2"><asp:Button ID="btnSend" runat="server" onclick="btnSend_Click" 
                OnClientClick="scroll()" Text="send" />
        </td></tr>        
        </table>

Can anyone please help me?

Here is a slightly modified version of @Darshan's script which uses jQuery. I like his solution because this 1 script will work with all UpdatePanels so you don't have to write code specifically for each and every UpdatePanel.

My modifications are:

  • Uses jQuery
  • Performs null checks
  • Doesn't pollute global namespace
  • Edit: Tabbing works as expected with TextBoxes with autopostback.

/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementId = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        if (fe != null) {
            focusedElementId = fe.id;
        } else {
            focusedElementId = "";
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementId != "") {
            $("#" + focusedElementId).focus();
        }
    });
});

Chosen.jQuery

This version will work with the Chosen jQuery plugin.

/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementSelector = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        focusedElementSelector = "";

        if (fe != null) {
            if (fe.id) {
                focusedElementSelector = "#" + fe.id;
            } else {
                // Handle Chosen Js Plugin
                var $chzn = $(fe).closest('.chosen-container[id]');
                if ($chzn.size() > 0) {
                    focusedElementSelector = '#' + $chzn.attr('id') + ' input[type=text]';
                }
            }
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementSelector) {
            $(focusedElementSelector).focus();
        }
    });
});

Ohh Ok The problem is that the ASP.NET Javascript methode "WebForm_AutoFocus(...)" is not execute after a partial page update, so you can't use the built in function SetFocus(clientID) in the codebhind class. My solution register two eventhandlers one for beginRequest and one for endRequest. In the event method "beginRequest" i save the client control id. In the endRequest method i use this value to set the focus, eg: CODE:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shipper.aspx.cs" Inherits="shipper" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Restore Focus after background postback</title>
    <script language="javascript">
      var postbackElement = null;
      function RestoreFocus(source, args)
      {
        document.getElementById(postbackElement.id).focus();
      }
      function SavePostbackElement(source, args)
      {
        postbackElement = args.get_postBackElement();
      }
      function AddRequestHandler()
      {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(RestoreFocus);
        prm.add_beginRequest(SavePostbackElement);
      }
    </script>
</head>
<body onload="AddRequestHandler()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
        <asp:UpdatePanel runat="server" ID="updPanel1">
          <ContentTemplate>
            <asp:Panel ID="panel1" runat="server">
                <asp:RadioButtonList ID="rbList" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Rb 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Rb 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Rb 3" Value="3"></asp:ListItem>
                  <asp:ListItem Text="Rb 4" Value="4"></asp:ListItem>
                  <asp:ListItem Text="Rb 5" Value="5"></asp:ListItem>
                </asp:RadioButtonList><br />
                <asp:DropDownList ID="ddSample" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
                </asp:DropDownList>
            </asp:Panel>
          </ContentTemplate>
        </asp:UpdatePanel>
      </div>
    </form>
</body>
</html>

在timerChat_Tick事件.do这....

txtChatBox.Focus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM