使用SweetAlerts对话框确认

时间:2018-06-19 08:27:06

标签: c# asp.net-core-mvc sweetalert asp.net-core-2.1

我是ASP.Net Core 2.1 MVC和C#的新手, 我无法弄清楚代码有什么问题。 我在任何帖子操作之前使用Sweet Alerts作为对话确认, 它可以工作,但它会立即重定向到索引页面,下面的行甚至没有正确执行。

  

swal("已保存!","您的记录已保存。","成功");

我希望只有在用户点击“确定”后才能重定向到索引页面。警报正常关闭(如淡出)

$(function () {
    $("#btnSave").click(function (e) {
        e.preventDefault();
        swal({
            title: "Save Changes?",
            text: "",
            type: "info",
            showCancelButton: true,
            cancelButtonClass: 'btn-secondary waves-effect',
            confirmButtonClass: 'btn-success waves-effect waves-light',
            confirmButtonText: "Yes",
            closeOnConfirm: false
        }, function () {
            $("#studentForm").submit();
            swal("Saved!", "Your record has been saved.", "success");
        });
    });
});

我尝试切换线

  

$("#studentForm&#34)。提交();

     

swal("已保存!","您的记录已保存。","成功");

  

swal("已保存!","您的记录已保存。","成功");

     

$("#studentForm&#34)。提交();

但它没有用。

这是我的编辑视图:

@model CIMS.Models.Plans

@{
    ViewData["Title"] = "Edit";
}



<div class="row">
    <div class="col-xs-12">
        <div class="page-title-box">
            <h4 class="page-title">Edit Plan</h4>

            <div class="clearfix"></div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-12">
        <div class="card-box table-responsive">
            <form asp-action="Edit" id="studentForm">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <input type="hidden" asp-for="PlanID" />
                <div class="form-group">
                    <label asp-for="PlanName" class="control-label">Plan Name</label>
                    <input asp-for="PlanName" class="form-control" />
                    <span asp-validation-for="PlanName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Description" class="control-label"></label>
                    <input asp-for="Description" class="form-control" />
                    <span asp-validation-for="Description" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="BillCutOffLimit" class="control-label">Bill Cut-off Limit</label>
                    <input asp-for="BillCutOffLimit" class="form-control" />
                    <span asp-validation-for="BillCutOffLimit" class="text-danger"></span>
                </div>

                <br />
                <div class="form-group">
                    <button type="submit" value="Save" class="btn btn-success waves-effect waves-light w-sm" id="btnSave">
                        <span class="btn-label"><i class="fa fa-check"></i></span>
                        Save
                    </button>
                    <a asp-action="Index" class="btn btn-primary waves-effect waves-light w-sm">
                        <span class="btn-label"><i class="fa fa-arrow-left"></i></span>
                        Back
                    </a>
                </div>
            </form>


        </div>
    </div>
</div>

这是控制器下的http post编辑操作:

// POST: Plans/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(string id, [Bind("PlanID,PlanName,Description,BillCutOffLimit,ModifiedBy,DateModified,ModifiedByComputerUsed")] Plans plans)
        {
            if (id != plans.PlanID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Attach(plans);

                    plans.ModifiedBy = User.Identity.Name;
                    plans.DateModified = DateTime.Now;
                    plans.ModifiedByComputerUsed = Environment.MachineName;

                    _context.Entry(plans).Property(x => x.PlanName).IsModified = true;
                    _context.Entry(plans).Property(x => x.Description).IsModified = true;
                    _context.Entry(plans).Property(x => x.BillCutOffLimit).IsModified = true;

                    _context.Entry(plans).Property(x => x.DateModified).IsModified = true;
                    _context.Entry(plans).Property(x => x.ModifiedBy).IsModified = true;
                    _context.Entry(plans).Property(x => x.DateModified).IsModified = true;

                    //_context.Update(plans);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PlansExists(plans.PlanID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(plans);
        }

任何想法?

1 个答案:

答案 0 :(得分:1)

不确定使用的是sweetalert.js的哪个版本,但以下代码适用于https://sweetalert.js.org/的2.1.0

您需要对Sweetalert使用基于Promise的设计。当您在保存更改之前单击第一个confirm时,它会返回Promise的布尔值,表示用户是否已确认操作。您需要解决对这个布尔值进行检查的承诺。基于该值,您需要创建另一个swal实例,并类似地对其进行解析以进行如下所示的Ajax调用-

Ajax调用的示例代码

$(function () {
        $("#btnSave").click(function (e) {
            e.preventDefault();
            swal({
                title: "Save Changes?",
                text: "",
                type: "info",
                showCancelButton: true,
                cancelButtonClass: 'btn-secondary waves-effect',
                confirmButtonClass: 'btn-success waves-effect waves-light',
                confirmButtonText: "Yes",
                closeOnConfirm: false
            })
            .then(val => {
               if (!val) throw null;
               swal("Saved!", "Your record has been saved.", "success")
                 .then((confirm) => {
                  $("#studentForm").submit();
                })            
            });
        });
        
       $("#studentForm").on('submit',function(){
         alert('form POST');
       })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<link href="http://tristanedwards.me/u/SweetAlert/lib/sweet-alert.css" rel="stylesheet"/>
<form id="studentForm" method="POST">
 name : <input type="text" id="fullname" /> <br>
 <button id="btnSave">
 Save
 </button>
</form>

正在工作的小提琴:http://jsfiddle.net/3e7fgtop/