ASP.NET-在离开页面或切换选项卡之前警告用户有关未保存的更改

时间:2018-09-05 15:40:54

标签: jquery asp.net tabs

我有一个用ASP.NET开发的应用程序,其中的主屏幕显示有不同的选项卡(我正在使用JQuery选项卡顺便说一句:https://jqueryui.com/tabs/)。每个选项卡均指向不同的局部视图。这些选项卡中的两个选项卡包含一组输入字段,每个输入字段均用“保存”按钮填充。我想警告用户,以防他更改了这些输入之一并且没有保存。

这是我的Javascript代码:

var somethingChanged = false;

    $('#formDadosPessoais input').change(function () {
        somethingChanged = true;
    });
    $('#formDadosPessoais select').change(function () {
        somethingChanged = true;
    });

    $(window).bind('beforeunload', function (e) {
        if (somethingChanged)
            return "Voçê efectuou alterações nos seus dados pessoais e não guardou as alterações.";
        else
            e = null; // i.e; if form state change show warning box, else don't show it.
    });

我测试了它,当我注销,关闭页面或刷新时它可以工作。但是,当我切换标签时它不起作用。例如,如果我更改选项卡1中的输入并切换到另一个选项卡,则会弹出警告。

我如何调整代码以解决这种情况?

以下是我的标签页的HTML,以备不时之需:

<div id="tabs" style="margin-top:20px;">
        <ul>
            <li><a href="#tabs-1">Personal Data</a></li>
            <li><a href="#tabs-2">Inquiry</a></li>
            <li><a href="#tabs-3">Candidature</a></li>
            <li><a href="#tabs-4">Documents</a></li>
            <li><a href="#tabs-5">Declaration</a></li>
        </ul>
        <div id="tabs-1">
            @Html.Action("Index", "PersonalData")
        </div>
        <div id="tabs-2">
            @Html.Action("Index", "Inquiry")
        </div>
        <div id="tabs-3">
            @Html.Action("Index", "Candidature")
        </div>
        <div id="tabs-4">
            @Html.Action("Index", "Documents")
        </div>
        <div id="tabs-5">
            @Html.Action("Index", "Declaration")
        </div>
    </div>

1 个答案:

答案 0 :(得分:1)

切换标签不会触发beforeunload,因此您还需要插入标签api的beforeActivate handle

$( "#tabs" ).tabs({
  beforeActivate: function( event, ui ) {
      if (somethingChanged && !confirm("Voçê efectuou alterações nos seus dados pessoais e não guardou as alterações.")
        return false;
        //can ignore else as they said ok to change
  }
});

编辑:

修改后的示例,在返回false之前显式调用确认框。返回false取消激活事件,因此选项卡不会切换。返回true是默认行为,它将切换选项卡。