我有一个Asp.net WebForm,它的代码很简单:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Test.aspx.cs" Inherits="NetmedWeb.Test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function quit() { event.returnValue = "Confirm?" }
</script>
</head>
<body onbeforeunload="quit(); return 'Sure?';">
<div>
Try to close me !!!
</div>
</body>
</html>
</asp:Content>
如果我试图关闭浏览器,或者关闭一个页面,即使我更改了页面,脚本也能正常工作。然而,我希望脚本只在某些情况下激活,而不是总是在C#代码端激活。例如:
private void TestScript()
{
if (mycondition)
{
Activate script
}
}
有可能做到这一点吗?例如
您必须进行AJAX调用来告诉后端该事件正在发生。查看此帖子:
https://stackoverflow.com/a/3428398/2941659
您可以简单地在<body>
标记中放入一个变量。
<body onbeforeunload="<%= unload %>">
然后在需要时从后面的代码中将其设置为脚本
public string unload = "";
protected void Page_Load(object sender, EventArgs e)
{
if (condition)
{
unload = "quit(); return 'Sure?';";
}
}