问题
I am developing an ASP MVC 5 web application using SQL Server. I am trying to delete a profile (client in database) via a button with javascript function.
Clicking on the button, the profile is deleted but the validation dialog doesn't appear. I don't know what the reason is but I doubt that there is an issue with the javascript code.
I tried also to create another button without submit, in order to verify the sweetAlert process. And it worked well.
This is my View :
@using (Html.BeginForm("Delete", "Client", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<input type="submit" value="Delete" class="btn btn-default" onclick="remove()">
}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">function remove() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover your profile!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your profile has been deleted!", {
icon: "success",
});
} else {
swal("Your profil is safe!");
}
});
}
</script>
My Controller :
[HttpPost]
public ActionResult Delete(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.DeleteClient(id))
{
TempData["Message"]= "Client Deleted Successfully";
}
Session.Abandon();
return RedirectToAction("Index", "Home");
}
catch
{
return View();
}
}
UPDATE : View :
<input type="button" value="Delete" class="btn btn-default" onclick="remove()">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
function remove() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover your profile!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
type: "POST",
url: "/Client/Delete",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Poof! Your profile has been deleted!", {
icon: "success",
}).then(function () {
window.location.href = "/Home/Index"
});
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
else {
swal("Your profil is safe!");
}
});
}
</script>
回答1:
You are trying to update onclick default behavior but you're not using preventDefault in your javascript code.
event.preventDefault()
来源:https://stackoverflow.com/questions/48091989/how-to-show-sweetalert-validation-delete-dialog-in-asp-mvc