简体   繁体   English

异步回发后如何保持对同一控件的关注?

[英]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. 我有3个文本框,一个在updatepanel中,它将每4秒刷新一次。 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. 这是使用jQuery的@Darshan脚本的略微修改版本。 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. 我喜欢他的解决方案,因为这个1脚本可以与所有UpdatePanel一起使用,因此您不必专门为每个UpdatePanel编写代码。

My modifications are: 我的修改是:

  • Uses jQuery 使用jQuery
  • Performs null checks 执行空检查
  • Doesn't pollute global namespace 不会污染全局命名空间
  • Edit: Tabbing works as expected with TextBoxes with autopostback. 编辑: Tab键按预期使用带有自动后备的TextBox。

/* 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 Chosen.jQuery

This version will work with the Chosen jQuery plugin. 此版本将与Chosen jQuery插件一起使用。

/* 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. 哦好的问题是ASP.NET Javascript方法“WebForm_AutoFocus(...)”在部分页面更新后没有执行,所以你不能在codebhind类中使用内置函数SetFocus(clientID)。 My solution register two eventhandlers one for beginRequest and one for endRequest. 我的解决方案为beginRequest注册了两个eventhandler,为endRequest注册了一个。 In the event method "beginRequest" i save the client control id. 在事件方法“beginRequest”中,我保存客户端控件ID。 In the endRequest method i use this value to set the focus, eg: CODE:- 在endRequest方法中,我使用此值来设置焦点,例如: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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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