简体   繁体   English

Asp.NET:如何在嵌套的“更新面板”中保持对文本框的关注

[英]Asp.NET: How to keep focus on textbox in a nested Update Panel

I am working on making a semi simple post and reply/forum pages in asp.net(with C#). 我正在asp.net(使用C#)中制作一个半简单的帖子和回复/论坛页面。 Everything works however when I went to add update panels it makes me want to throw my head into a wall. 一切正常,但是当我去添加更新面板时,这使我想把头扔到墙上。

I use a DataList to display the posts. 我使用DataList来显示帖子。 I use a form consisting of two textboxes and a button to insert a new post. 我使用由两个文本框和一个按钮组成的表单来插入新帖子。 One textbox if for the name, and the other for the message. 一个文本框(如果用于输入名称),另一个文本框用于显示消息。

First update panel I added (nested) is to provide a character count for the post. 我添加(嵌套)的第一个更新面板是为帖子提供字符数。 I have a label in the Content and it is triggered by the textboxes textchanged event. 我在内容中有一个标签,它由文本框textchanged事件触发。 The textbox 'txtMessage' also has a java-script function run 'onkeyup' to keep the focus on the textbox when typing. 文本框“ txtMessage”还具有运行“ onkeyup”的java脚本功能,以在键入时将焦点集中在文本框上。 I limit the characters at 1000. 我限制字符为1000。

The next update is to surround the DataList so that it does not post back everytime (if not used and the back button is hit it will go back and visually remove each post which is not a good design practice). 下一个更新是围绕DataList,这样它就不会每次都回发(如果不使用并且按下后退按钮,它将回退并从视觉上删除每个发回的信息,这不是一个好的设计实践)。 However when I just put the panel around the DataList it did not postback the insert form so the boxes were not cleared. 但是,当我将面板放在DataList周围时,它没有回发插入表单,因此没有清除这些框。 Which I would like to be done, so I wrapped everything then by this updatepanel, which then made the character count update panel nested by this one. 我想完成此操作,因此我将所有内容包装在此updatepanel中,然后将字符计数更新面板嵌套在此面板中。 This now works, but the focus is taken off of the txtMessage box each time the textchanged event fires. 现在可以使用,但是每次textchanged事件触发时,焦点都从txtMessage框移开。 So the JavaScript is not firing now? 所以JavaScript现在不触发了吗?

I have moved the opening and closing of the update panel countless times and have tried different fixes, so any further suggestions would help. 我无数次地打开和关闭了更新面板,并尝试了不同的修复方法,因此任何进一步的建议都将有所帮助。 The code is below. 代码如下。

ForumT.aspx ForumT.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForumT.aspx.cs" Inherits="UPE_Site_v1.ForumT" %>

<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headPlaceHolder" runat="server">
<script type="text/javascript">
    function reFocus(id) {
        __doPostBack(id, '');
        document.getElementById(id).blur();
        document.getElementById(id).focus();
    }
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="contentPlaceHolder" runat="server">

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetPosts" TypeName="TimeTrackerRepository" DataObjectTypeName="System.Guid" DeleteMethod="DeletePost">    </asp:ObjectDataSource>




<asp:UpdatePanel ID="upDataList" runat="server" UpdateMode="Conditional">
    <ContentTemplate>

        <div>
            <asp:DataList ID="DataList2" runat="server" CellPadding="4" DataSourceID="ObjectDataSource1"
                ForeColor="#333333" OnItemCommand="DataList2_ItemCommand" OnItemDataBound="DataList2_ItemDataBound"
                DataKeyField="PostID" OnItemCreated="DataList2_ItemCreated">
                <AlternatingItemStyle BackColor="White" />
                <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <ItemStyle BackColor="#D4EBD4" />
                <ItemTemplate>
                    <div class="row">
                        <div class="col-xs-12 col-sm-6">
                            Name: <strong><%# Eval("Name") %></strong>
                        </div>
                        <div class="col-xs-12 col-sm-6">
                            <%# Eval("TimePosted") %>
                        </div>
                        <div class="col-xs-12" style="word-break: break-all">
                            <%# Eval("Message") %>
                        </div>
                    </div>

                    <br />
                    <asp:Button ID="btnDelete" CssClass="btn btn-warning" runat="server" Text="Delete" CommandArgument='<%# Eval("PostID") %>' CommandName="DeleteItem" />
                    <asp:LinkButton CssClass="btn btn-primary" ID="lkbtnFullPost" runat="server" Text="See Full Post" CommandArgument='<%# Eval("PostID") %>' CommandName="FullPost"></asp:LinkButton>
                </ItemTemplate>
                <SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            </asp:DataList>

        </div>

        <%--</ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
                </Triggers>
    </asp:UpdatePanel>--%>

        <br />
        <br />

        <div class="row">
            <div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">
                <p>Add a post to this forum:</p>
                <div class="form-group">
                    <asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
                    <asp:TextBox CssClass="form-control" ID="txtName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
                        ErrorMessage="This is a required field." ValidationGroup="Application"
                        Display="Dynamic" ForeColor="Red">
                    </asp:RequiredFieldValidator>
                </div>

                <%--<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
                <ContentTemplate>--%>

                <div class="form-group">
                    <asp:Label ID="Label2" runat="server" Text="Message: ">    </asp:Label>
                    <asp:TextBox onkeyup="reFocus(this.id);" CssClass="form-control" ID="txtMessage" runat="server" TextMode="MultiLine" Rows="4" OnTextChanged="txtMessage_TextChanged"></asp:TextBox>

                    <asp:RequiredFieldValidator runat="server" ControlToValidate="txtMessage"
                        ErrorMessage="This is a required field." ValidationGroup="Application"
                        Display="Dynamic" ForeColor="Red">
                    </asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator runat="server" ControlToValidate="txtMessage"
                        ErrorMessage="Character limit is 1000 characters."
                        ValidationGroup="Application" Display="Dynamic" ForeColor="Red"
                        ValidationExpression=".{0,1000}">
                    </asp:RegularExpressionValidator>
                </div>

                <br />
                <%--</div>
    </div>--%>
                <%--</ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
                </Triggers>
    </asp:UpdatePanel>--%>
                <%--<div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">--%>
                <asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:Label ID="lblCharacterCount" runat="server">0/1000</asp:Label>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="txtMessage" EventName="TextChanged" />
                    </Triggers>
                </asp:UpdatePanel>
                <asp:Button ValidationGroup="Application" CssClass="btn btn-default" ID="btnPost" runat="server" Text="POST IT" OnClick="btnPost_Click" />
                <asp:Label ID="lblError" runat="server" Text="" CssClas="Error" ForeColor="Red"></asp:Label>

            </div>
        </div>

        <br />
        <br />
        <br />
    </ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

ForumT.aspx.cs ForumT.aspx.cs

only including the textchanged event 仅包括textchanged事件

protected void txtMessage_TextChanged(object sender, EventArgs e)
    {

        lblCharacterCount.Text = txtMessage.Text.Count().ToString() + "/1000";
        if (txtMessage.Text.Count() >= 1000)
        {
            lblCharacterCount.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblCharacterCount.ForeColor = System.Drawing.Color.Black;
        }
    }

Sorry for the code being a little sloppy. 对不起,代码有点草率。 Also side not, I am using bootstrap so that is what all of the div's are for 另外不是,我正在使用引导程序,所以所有div都用于

I was facing the same issue as I needed to set focus on the textbox after postbacks in update panel. 在更新面板中进行回发后,我面临着与需要将重点放在文本框上相同的问题。 So I researched over internet & found this Javascript code. 因此,我通过互联网进行了研究,并找到了此Javascript代码。 I tried it & it is working perfectly. 我试过了,它工作正常。 It adds event listener for update panel for before & after postback. 它在回发之前和之后为更新面板添加了事件侦听器。 Gets textbox id before postback & set it after completion of postback. 在回发之前获取文本框ID,并在回发完成后进行设置。

    var lastFocusedControlId = "";

    function focusHandler(e) {
        document.activeElement = e.originalTarget;
    }

    function appInit() {
        if (typeof (window.addEventListener) !== "undefined") {
            window.addEventListener("focus", focusHandler, true);
        }
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
    }

    function pageLoadingHandler(sender, args) {
        lastFocusedControlId = typeof (document.activeElement) === "undefined"
            ? "" : document.activeElement.id;
    }

    function focusControl(targetControl) {
        if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
            var focusTarget = targetControl;
            if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
                oldContentEditableSetting = focusTarget.contentEditable;
                focusTarget.contentEditable = false;
            }
            else {
                focusTarget = null;
            }
            targetControl.focus();
            if (focusTarget) {
                focusTarget.contentEditable = oldContentEditableSetting;
            }
        }
        else {
            targetControl.focus();
        }
    }

    function pageLoadedHandler(sender, args) {
        if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
            var newFocused = $get(lastFocusedControlId);
            if (newFocused) {
                focusControl(newFocused);
            }
        }
    }

    Sys.Application.add_init(appInit);

Just use this code in your script on aspx page. 只需在aspx页面上的脚本中使用此代码即可。

You say your javascript is not working. 您说您的JavaScript无法正常工作。 When using update panels and js you will need to rebind your js subscribed events. 使用更新面板和js时,您将需要重新绑定js订阅的事件。

Reference: jQuery $(document).ready and UpdatePanels? 参考: jQuery $(document).ready和UpdatePanels?

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

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