Maintaining focus on ajax update panel after updating form

房东的猫 提交于 2019-12-06 11:04:00

For things like this, I often stash the value in an asp:Hidden control (input type="hidden") using the javascript and then add a pageLoad function (in the javascript) to parse that field and then set the focus. This way the id of the focused control is persisted through the postback.

Something like this (pseudocode):

<input type="hidden" id="focusHolder" />

function onSubmit (registered via ClientScript.RegisterOnSubmitStatemnet) {
grab the target and stash id in #focusHolder
}

function pageLoad() {
$get($get('focusHolder').value).focus();
}

You can do it on server side too. Here is an example of how to put focus on the control that caused the asynchronous postback:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
            {
                string IDPostbackCtrl = GetAsyncPostBackControlID(Page, Page.Request);
                ScriptManager.GetCurrent(Page).SetFocus(IDPostbackCtrl);
            }
        }
    }

    public string GetAsyncPostBackControlID(Page page, HttpRequest request)
    {
        string smUniqueId = ScriptManager.GetCurrent(page).UniqueID;
        string smFieldValue = request.Form[smUniqueId];

        if (!String.IsNullOrEmpty(smFieldValue) && smFieldValue.Contains('|'))
            return smFieldValue.Split('|')[1];

        return String.Empty;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!