Maintaining focus on ajax update panel after updating form

二次信任 提交于 2020-01-02 08:54:30

问题


I've have a formview that is designed to update it's datasource each time a text_changed event or dropdown list has been changed. On every text_changed event and equivalent for other controls I call the formView.UpdateItem method and this causes the form to lose focus from the control I have tabbed down to.

I've tried to implement this method but I get unknown runtime errors after I have tried to select a control for the second time.

I can't help but think there is another way of dealing with this.

How would you go about solving this issue?


回答1:


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();
}



回答2:


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;
    }


来源:https://stackoverflow.com/questions/853390/maintaining-focus-on-ajax-update-panel-after-updating-form

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