如何设置焦点以控制发起的回发

时间:2016-04-05 14:37:11

标签: asp.net focus postback

避免无根据的重复"标记,让我先说 - 我已经搜索了高和低的答案,只找到像this这样没有答案的人,或者this,它告诉我使用MyControl.Focus();我的代码背后。 可以正常工作。我会解释一下。

我在更新面板中有一系列下拉控件,每个控件都会影响后面的控件 - City,Building和Room。当用户更改城市下拉列表,鼠标或键盘中的选择时,焦点会立即丢失,因为页面会执行部分回发。好的,所以我尝试放入CityListDropDown.Focus();,但这会导致页面重新定位,以便此控件位于页面可见区域的底部 - 而不是所需的行为。页面根本不应该移动。请注意,只有在更新面板之前页面上有很多其他内容时才这一点很重要,这样这些提示会降低到页面必须向下滚动到它们的位置。

那么,如何将焦点恢复到该城市下拉,以便当用户使用键盘时,他们可以继续卡车运行到下一个提示?同样适用于建筑物下拉。

这是我的HTML:

            <asp:UpdatePanel ID="RoomsUpdatePanel" runat="server" UpdateMode="Conditional" RenderMode="Inline">
                <ContentTemplate>
                                <asp:DropDownList ID="CityListDropDown" runat="server" class="form-control input-sm" Width="140" AutoPostBack="True" OnSelectedIndexChanged="CityListDropDown_SelectedIndexChanged">
                                </asp:DropDownList>
                                <asp:DropDownList ID="BuildingListDropDown" runat="server" class="form-control input-sm" AutoPostBack="True" Width="100" OnSelectedIndexChanged="BuildingListDropDown_SelectedIndexChanged">
                                </asp:DropDownList>
                                <asp:DropDownList ID="RoomListDropDown" runat="server" class="form-control input-sm" AutoPostBack="False" Width="175">
                                </asp:DropDownList>
                </ContentTemplate>
            </asp:UpdatePanel>

这是我背后的代码:

    protected void CityListDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBuildingList();
        LoadRoomList();
        CityListDropDown.Focus();
    }

    protected void BuildingListDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadRoomList();
        BuildingListDropDown.Focus();
    }

2 个答案:

答案 0 :(得分:0)

如果您不希望每次更改焦点时页面都滚动/重新定位,您可以使用Page指令的PageMaintainScrollPositionOnPostback属性:

<%@ PageMaintainScrollPositionOnPostback="true" ... %>

或者您可以尝试通过代码以编程方式设置它:

Page.MaintainScrollPositionOnPostBack = true;

答案 1 :(得分:0)

我明白了!因此,使用控件的Focus()方法后面的代码会导致页面重新定位,即使您已将页面的MaintainScrollPositionOnPostBack属性设置为true。但是,javascript可以在不必要地移动页面的情况下改变焦点。因此,如果我需要将焦点从后面的代码重置为发送控件,我可以这样做:

    protected void CityListDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBuildingList();
        LoadRoomList();
        ScriptManager.RegisterStartupScript(CityListDropDown, CityListDropDown.GetType(), "CityDropDownRefocus", "document.getElementById(\"" + CityListDropDown.ClientID + "\").focus();", true);
    }

或者,如果我希望重置焦点的那行代码更通用(比如我有一个由多个控件使用的事件处理程序,我需要处理程序将焦点重置为生成回发的控件,处理程序将获取发送对象,所以我可以说:

protected void MyControlHandler(object sender, EventArgs e)
{
    ...
    ScriptManager.RegisterStartupScript((WebControl)sender, sender.GetType(), "CityDropDownRefocus", "document.getElementById(\"" + ((WebControl)sender).ClientID + "\").focus();", true);
}

然后将焦点重置回发送控件,而不移动页面!