Introduction
Performing a POST operation using .NET Core, Ajax, and SweetAlert is a powerful way to enhance your web applications. This blog post will guide you through the steps to create a form, use SweetAlert for user confirmation, and make an Ajax POST request to a .NET Core backend.
Table of Contents
Setting Up the .NET Core Project
First, you need to create a .NET Core project. Follow these steps to set up your project:
- Open Visual Studio and create a new ASP.NET Core Web Application.
- Choose the Web Application (Model-View-Controller) template.
- Name your project and solution, then click Create.
Creating the Form
Let’s create a simple form in your Razor view where users can enter data. Add a new Razor view named Index.cshtml
to your project.
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary text-white">
<h3 class="card-title">Submit Your Data</h3>
</div>
<div class="card-body">
<form id="dataForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
Implementing SweetAlert for Confirmation
SweetAlert provides a sleek way to display alerts. Add SweetAlert to your project by including the following CDN link in your Index.cshtml
:
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
</head>
Now, let’s modify the form submission to show a SweetAlert confirmation before making the Ajax request. We will also ensure that the form cannot be submitted twice and show a loading animation during the process.
@section Scripts {
<script>
let isSubmitting = false;
document.getElementById('dataForm').addEventListener('submit', function(e) {
e.preventDefault();
if (isSubmitting) {
Swal.fire(
'Warning',
'The form is already being submitted. Please wait.',
'warning'
);
return;
}
Swal.fire({
title: 'Are you sure?',
text: "Do you want to submit this form?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, submit it!'
}).then((result) => {
if (result.isConfirmed) {
submitForm();
}
});
});
function submitForm() {
isSubmitting = true;
Swal.fire({
title: 'Submitting...',
text: 'Please wait while we process your data.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
onOpen: () => {
Swal.showLoading();
}
});
const formData = new FormData(document.getElementById('dataForm'));
$.ajax({
url: '/Home/SubmitData',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
isSubmitting = false;
Swal.close();
if (response.success) {
Swal.fire(
'Submitted!',
'Your form has been submitted.',
'success'
);
} else {
Swal.fire(
'Error!',
response.message,
'error'
);
}
},
error: function(error) {
isSubmitting = false;
Swal.close();
Swal.fire(
'Error!',
'There was an error submitting your form.',
'error'
);
}
});
}
</script>
}
Explanations
- isSubmitting Variable: A variable
isSubmitting
is defined to track whether the form is currently being submitted. If the form is already being submitted, a warning message is displayed, and the second submission attempt is prevented. - SweetAlert Customizations:
- When the user attempts to submit the form, a SweetAlert confirmation dialog is shown.
- If the user confirms, the
submitForm
function is called. - The
submitForm
function shows a loading animation indicating that the form is being processed.
- Ajax Request:
- The Ajax request starts by setting the
isSubmitting
variable totrue
. - The
Swal.fire
method shows a loading animation while the form data is being submitted. - Upon successful submission, the loading animation is closed, and a success message is displayed.
- If there is an error, the loading animation is closed, and an error message is shown.
- The
isSubmitting
variable is reset tofalse
after the Ajax request completes, allowing the form to be submitted again if necessary.
- The Ajax request starts by setting the
Handling the POST Request in .NET Core
Now, let’s handle the POST request in the .NET Core backend. Open the HomeController.cs
file and add the SubmitData
action method.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SubmitData([FromForm] FormDataModel model)
{
if (ModelState.IsValid)
{
// Process the data
return Json(new { success = true, message = "Data submitted successfully!" });
}
return Json(new { success = false, message = "Invalid data!" });
}
}
public class FormDataModel
{
public string Name { get; set; }
public string Email { get; set; }
}
In this example, the SubmitData
action method receives the form data, validates it, and processes it. The FormDataModel
class represents the data structure.
Conclusion
By following this guide, you can perform a POST operation using .NET Core, Ajax, and SweetAlert. This setup enhances user experience by providing a confirmation step before submitting data and handling the form submission seamlessly with Ajax.