Search code examples
c#asp.net-core-mvcsweetalertasp.net-core-2.1

Using SweetAlerts dialog confirmations


I'm new to ASP.Net Core 2.1 MVC and C#, I couldn't figure out what's wrong with the code. I'm using Sweet Alerts as dialog confirmation before any post actions, it works but it redirects instantly to the index page, the line below didn't even executed properly.

swal("Saved!", "Your record has been saved.", "success");

I want it to redirect to the index page only after the user clicks 'OK' and the alert closed properly (like fade out)

$(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");
        });
    });
});

I tried switching the lines

$("#studentForm").submit();

swal("Saved!", "Your record has been saved.", "success");

to

swal("Saved!", "Your record has been saved.", "success");

$("#studentForm").submit();

but it didn't work.

This is my Edit view:

@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>

and this is the http post edit action under the controller:

// 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);
        }

any idea?


Solution

  • Not sure which version of sweetalert.js you are using but the below code works with 2.1.0 of https://sweetalert.js.org/

    You need to use the Promise based design for sweetalert . When you click on the first confirm before saving the changes it returns a Promise of boolean value which signifies whether the user has confirmed the action or not. You need to resolve the promise to check this boolean value.Based on this value you need to create another instance of swal and similarly resolve it to make the Ajax call like below -

    sample code for Ajax call

    $(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>

    Working fiddle : http://jsfiddle.net/3e7fgtop/