I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below is a brief sample to illustrate the problem:
<%@ Page Language="C#" EnableEventValidation="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script runat="server">
public IEnumerable<int> Measurements_GetData()
{
return new[] { 123, 328, 1099 };
}
</script>
</head>
<body>
<form method="post" runat="server">
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<h1>OK</h1>
<div>
<asp:TextBox ID="Measurement1" runat="server" Text="123" AutoPostBack="true" />
</div>
<div>
<asp:TextBox ID="TextBox1" runat="server" Text="328" AutoPostBack="true" />
</div>
<div>
<asp:TextBox ID="TextBox2" runat="server" Text="1099" AutoPostBack="true" />
</div>
<h1>Not OK</h1>
<asp:Repeater ID="Measurements" runat="server" SelectMethod="Measurements_GetData" ItemType="System.Int32">
<ItemTemplate>
<div>
<asp:TextBox ID="Measurement" runat="server" AutoPostBack="true" Text="<%# Item %>" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</form>
<script type="text/javascript">
(function () {
var focusedElementId = "";
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(function (source, args) {
// re-focus element, if any selected prior to postback
if (focusedElementId !== "") {
document.getElementById(focusedElementId).focus();
console.log("focus:" + focusedElementId);
}
});
prm.add_pageLoading(function (source, args) {
var fe = document.activeElement;
focusedElementId = fe !== null ? fe.id : "";
});
})();
</script>
</body>
</html>
In this example, you can observe both the functional and non-functional behavior. When interacting with the first text boxes, focus is correctly preserved as intended. However, when working with the text input in the repeater section, focus is lost due to a mysterious full postback being triggered.
This peculiar behavior seems to indicate a potential bug within web forms. If indeed it is a bug, are there any known workarounds to address this issue?