Sir,
some time user click on submit button and immediate click on reload button on browser and system apply submit function twice. i want to prevent browser reload button in asp.net (aspx)
please help
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AtestPreventReloadPage.aspx.cs" Inherits="AtestPreventReloadPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Prevent Page Reload</title>
<style>
#customModal {
display: none;
position: fixed;
z-index: 9999;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
#modalContent {
background-color: white;
margin: 15% auto;
padding: 20px;
width: 300px;
text-align: center;
border-radius: 5px;
box-shadow: 0 0 10px #333;
}
#cancelBtn {
padding: 8px 16px;
background-color: #d9534f;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
</style>
<script type="text/javascript">
let isDirty = false;
window.onload = function () {
const txtUserData = document.getElementById('<%= txtUserData.ClientID %>');
txtUserData.addEventListener('input', function () {
isDirty = true;
});
// Native browser warning on unload
window.addEventListener('beforeunload', function (e) {
if (isDirty) {
e.preventDefault();
e.returnValue = '';
}
});
// Intercept F5 and Ctrl+R
document.addEventListener('keydown', function (e) {
if (isDirty && (e.key === 'F5' || (e.ctrlKey && e.key.toLowerCase() === 'r'))) {
e.preventDefault();
showModal();
}
});
// Intercept link clicks and submit buttons
document.querySelectorAll('a, input[type=submit], button[type=submit]').forEach(el => {
el.addEventListener('click', function (e) {
if (isDirty) {
e.preventDefault();
showModal();
}
});
});
};
function showModal() {
document.getElementById('customModal').style.display = 'block';
}
function hideModal() {
document.getElementById('customModal').style.display = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="padding: 20px;">
<h1>Data Entry Page</h1>
<p>Enter some data below. If you try to reload or leave the page, a warning will appear with only a Cancel button.</p>
<asp:TextBox ID="txtUserData" runat="server" TextMode="MultiLine" Rows="5" Columns="60" placeholder="Enter some important text here..."></asp:TextBox>
<br /><br />
<asp:Button ID="btnSave" runat="server" Text="Save Data" />
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Green"></asp:Label>
</div>
</form>
<!-- Custom Modal -->
<div id="customModal">
<div id="modalContent">
<p><strong>Warning:</strong> You have unsaved changes.<br />Please save your work before leaving.</p>
<button id="cancelBtn" onclick="hideModal()">Cancel</button>
</div>
</div>
</body>
</html>