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

本文关键字:文本 NET 更新 嵌套 Asp | 更新日期: 2023-09-27 18:00:25

我正在asp.net(使用C#)中制作一个半简单的帖子和回复/论坛页面。然而,当我添加更新面板时,一切都正常了,这让我想把头撞到墙上。

我使用DataList来显示帖子。我使用一个由两个文本框和一个按钮组成的表单来插入一个新帖子。一个文本框用于显示姓名,另一个用于显示信息。

我添加(嵌套)的第一个更新面板是为帖子提供一个字符计数。我在内容中有一个标签,它是由textboxes textchanged事件触发的。文本框"txtMessage"还有一个运行"onkeyup"的java脚本函数,用于在键入时将焦点放在文本框上。我把字符限制在1000个以内。

下一次更新是将DataList包围起来,这样它就不会每次都返回(如果不使用并点击返回按钮,它将返回并从视觉上删除每个帖子,这不是一个好的设计实践)。然而,当我只是把面板放在DataList周围时,它没有回发插入表单,所以框没有被清除。我想这样做,所以我用这个更新面板包装了所有内容,然后使字符计数更新面板嵌套在这个面板中。这现在起作用了,但每次触发textchanged事件时,焦点都会从txtMessage框中移开。那么JavaScript现在没有启动了?

我已经无数次移动了更新面板的打开和关闭,并尝试了不同的修复方法,所以任何进一步的建议都会有所帮助。代码如下。

论坛T.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>

论坛T.aspx.cs

仅包括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;
        }
    }

很抱歉代码有点草率。同样重要的是,我使用的是引导程序,这就是

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

的所有div

我遇到了同样的问题,因为我需要在更新面板中回发后将重点放在文本框上。所以我在互联网上进行了研究;找到了这个Javascript代码。我试过了&它运行得很好。它为before&回发后。获取回发前的文本框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);

只需在aspx页面上的脚本中使用此代码。

您说您的javascript不工作。当使用更新面板和js时,您需要重新绑定js订阅的事件。

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