ASP.NET: Find which element had focus before postback?

China☆狼群 提交于 2019-12-11 04:36:32

问题


I have a series of controls on a page, including some textboxes that serve to record employee timesheet. When OnTextChanged fires, the page postback and update the overall working hours and minutes.

The problem is, when the user clicks the save button, a postback happens, but it is not because of save button's action but because OnTextChanged has fired. The user believes that the saving has gone well until he/she access the page again and doesn't find his/her data. It's next to the impossible to explain to user that they need to click twice because the first time the textbox loses focus and the second time it's the right one.

Is there a way to store the value of the last element that had the focus before the postback occured? I've tried to access the value of __LASTFOCUS, but I'm getting an empty string.

string lastFocus = Page.Request.Params.Get("__LASTFOCUS"); 

Thanks for helping


回答1:


If you are trying to grab the last control that lost focus which has AutoPostBack="true", I believe you can get the Name of this control from Request.Form.Get("__EVENTTARGET"). This form variable contains the ID of any control invoking postback (in most, if not all, scenarios).




回答2:


I have a similar situation with a GridView with an arbitrary amount of textboxes, each with AutoPostBack on and OnTextChanged event handlers. What I wanted to do was be able to tab out of a textbox, postback, then restore focus to the textbox that had focus before postback e.g. the textbox that I tabbed to.

This is what I ended up with:

function RestoreFocus(source, args) {
        var val = $("#<%=postbackFocusID.ClientID %>").attr("value");
        var el = document.getElementById(val);
        if (el != null)
            el.focus();
    }
    function PersistElementThatHasFocus(source, args) {
        $("#<%=postbackFocusID.ClientID %>").attr("value", document.activeElement.id);
    }
    function AddRequestHandler() {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(RestoreFocus);
        prm.add_beginRequest(PersistElementThatHasFocus);
    }

The postbackFocusID is just an asp:HiddenField.



来源:https://stackoverflow.com/questions/13957036/asp-net-find-which-element-had-focus-before-postback

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