【问题标题】:Save data before leave the page in ASP.NET在 ASP.NET 中离开页面之前保存数据
【发布时间】:2016-06-08 11:00:06
【问题描述】:

我有 asp.net 页面。 我没有“保存”按钮(不是我的要求)。

我需要在离开此页面之前保存页面数据。

我尝试过使用 Page_Unload 之类的事件来实现它,但它不起作用...... 原因 Save 方法使用来自页面上元素的数据,例如 txtBox1.Text 我不能使用 .ashx 处理程序来保存一些 ajax (或者我不知道如何在处理程序中使用页面元素,因为它们是 @987654327 @)。

那么除了 serealizing 表单并将其传递给处理程序之外,还有其他解决方案吗?

【问题讨论】:

  • Page_Unload 是一个服务器端事件,在您的页面被发送到浏览器之前会被触发(为简单起见)。一旦您的浏览器接收到 html,该页面将不再存在,Page_Unload 将已被调用。所以这里没有用。 msdn.microsoft.com/en-us/library/ms178472.aspx
  • @freedomn-m,感谢您的解释

标签: javascript c# jquery asp.net webforms


【解决方案1】:

您可以使用onbeforeunload 事件。 它应该在卸载前触发。 它允许您回问用户是否真的想离开。检查类似的例子here

<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

作为回报,您可以保存所需的值。

或者,您可以在用户离开时发送Ajax 请求。

【讨论】:

  • 我已经阅读了这个 js 事件。但是我怎样才能从这个事件中调用页面上的方法呢?
  • 你可以获得PageMethods。例如PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
【解决方案2】:

我知道回答晚了,但对于仍在解决相同问题的人来说一点也不晚: 你只需要用更新面板包围你的执行功能区域,如下所示

  <asp:UpdatePanel runat="server" ID="blahblahId"> 
 <ContentTemplate>
<asp:Button  CssClass="hidden" runat="server" ID="btnAddInfo" OnClick="execBforeUnload"/>                                                    
 </ContentTemplate>
           <Triggers>
          <asp:AsyncPostBackTrigger  ControlID="btnAddInfo"/>                                      
              </Triggers>
        </asp:UpdatePanel>

你的 javascript 代码将是

  var unloadEvent = function (e)

    {
        alert("hi");
        __doPostBack("<%=btnAddInfo.ClientID%>", "");
    };
    window.addEventListener("beforeunload", unloadEvent);

最后你的 C# 方法如下:

   public void execBforeUnload(object sender ,EventArgs e)
    {
        Session[lblNumber.Text] = null;
        Application[lblNumber.Text] = null;
    }

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多