为什么MVC甜蜜警报将自动关闭

Why MVC Sweet Alert will Auto Close?

本文关键字:MVC 甜蜜 为什么      更新时间:2023-09-26

下面是我的编码。请告知为什么甜蜜警报只会弹出不超过 1 秒,然后自动重定向到另一个页面。

从 HTML:

$.ajax({
  url: "/ABC/AddST/",
  data: {
    "username": $("#username").val(),
    "fullname": $("#fullname").val()
  },
  type: "POST"
}).success(function(data) {
  swal({
    title: "Done!",
    text: "Sales Team was successfully added!",
    type: "success"
  }, function() {
    window.location.href = '/ABC/STList';
  });
}).error(function(data) {
  swal("Oops", "We couldn't connect to the server!", "error");
});

从控制器:

[HttpPost]
public ActionResult AddSalesTeam(string username, string fullname)
{
    var st = new Sales();
    if (ModelState.IsValid)
    {
        st.Username = username;
        st.FullName = fullname;
        db.User.Add(st);
        db.SaveChanges();
        return RedirectToAction("SalesTeamList");
    }
    return View();
}

你需要给它一个计时器。

swal({
  title: "Done!",
  text: "Sales Team was successfully added!",
  type: "success",
  timer: 1000, // Wait 1 second
  showConfirmButton: false // No reason to show the button
}, function() {
  window.location.href = '/ABC/STList';
});

据我从问题中了解到,您希望显示警报,然后在用户单击确认按钮时,然后重定向到/ABC/STList页面,(而不是自动重定向用户),对吗?㞖。你试过这个吗?

swal({
  title: "Done!",
  text: "Sales Team was successfully added!",
  type: "success",
  showCancelButton: false,
  confirmButtonText: "Ok",   
  closeOnConfirm: false
}, function() {
  window.location.href = '/ABC/STList';
});

====

======================

编辑:如果需要,您可以删除closeOnConfirm: false行,单击确定按钮后弹出窗口将关闭(但仍会被重定向)。只是因为最终用户最好看到单击按钮后弹出窗口已关闭。

在函数之前和之后添加 e.preventDefault() $ajax就可以了。

e.preventDefault();  
$.ajax({
  url: "/ABC/AddST/",
  data: {
    "username": $("#username").val(),
    "fullname": $("#fullname").val()
  },
  type: "POST"
}).success(function(data) {
  swal({
    title: "Done!",
    text: "Sales Team was successfully added!",
    type: "success"
  }, function() {
    window.location.href = '/ABC/STList';
  });
}).error(function(data) {
  swal("Oops", "We couldn't connect to the server!", "error");
});
e.preventDefault();