Title: Implementing AJAX for Adding or Saving Data to Database in ASP.NET MVC
Introduction: In this article, we will explore how to use AJAX to add or save student data to a database in an ASP.NET MVC application. We'll demonstrate how to use jQuery AJAX to communicate with the server, handle form data, and store it in the database using Entity Framework. The provided code illustrates a simple implementation that can serve as a foundation for more sophisticated data management tasks.
Prerequisites: Before proceeding with this tutorial, you should have a basic understanding of ASP.NET MVC, C#, jQuery, and Entity Framework.
Overview of the Code: The code example consists of three main parts: the jQuery AJAX function in JavaScript, the ASP.NET MVC controller method, and the repository class responsible for database operations.
jQuery AJAX Function
- The JavaScript code uses jQuery to handle the form submission. When the "SubmitButton" is clicked, the function collects data from checkboxes and serializes the form data. It then sends an AJAX POST request to the server.
$("#SumbitButton").click(function () {
var selected = []; // initialize array
$('div#languagesSection2 input[type=checkbox]').each(function () {
if ($(this).is(":checked")) {
selected.push($(this).attr("id"));
}
});
$("#Languages").val(selected);
var studentData = $("#studentInputForm").serialize();
if (!$('#studentInputForm').valid()) {
return false;
}
$.ajax({
url: "/Home/SaveStudent",
type: "POST",
data: studentData,
success: function (data) {
$('#studentInputForm').find(':input').val('');
$('input[type=checkbox]').prop('checked', false);
Notify("Data Added Successfully", null, null, 'success');
$(".popModel").removeClass("activePopModel");
oTable.ajax.reload();
},
error: function (errormessage) {
Notify("Error! Data Not Saved", null, null, 'danger');
console.log("error message");
}
});
});
ASP.NET MVC Controller Method
- The "HomeController" class acts as the controller responsible for handling incoming requests. The "SaveStudent" action method receives the form data as a parameter of the "StudentModel" type.
public class HomeController : Controller
{
OperationRepositery repo = null;
public HomeController()
{
repo = new OperationRepositery();
}
public ActionResult SaveStudent(StudentModel model)
{
var result = repo.AddData(model);
return Json(new { result = true }, JsonRequestBehavior.AllowGet);
}
}
Repository Class (Add Method)
- The "OperationRepository" class encapsulates the data access logic and implements the "AddData" method to add the student data to the database using Entity Framework.
class OperationRepositery
{
public int AddData(StudentModel model)
{
if (model != null)
{
using (var context = new StudentEntities())
{
StudentTable studentData = new StudentTable()
{
// Map properties from the model to the database entity
ID = model.ID,
Student = model.Student,
School = model.School,
Mark = model.Marks,
Rank = model.Rank,
Stream = model.Course,
Country = model.Country,
State = model.State,
City = model.City,
Languages = string.Join(",", model.Languages.Where(lang => lang.IsChecked).Select(lang => lang.ID))
};
context.StudentTable.Add(studentData);
context.SaveChanges();
return model.ID;
}
}
return model.ID;
}
}
Conclusion: In this article, we have learned how to implement an AJAX-based functionality to add or save student data to a database in an ASP.NET MVC application. The JavaScript AJAX function handles the form submission, serializes the data, and communicates with the server. The ASP.NET MVC controller receives the form data and passes it to the repository class, which, in turn, handles the database insertion using Entity Framework. Developers can build upon this example to enhance the application with additional features like validation, error handling, or even integrate it with other parts of their projects. Always remember to validate user input and implement security measures to protect the application from potential threats. Happy coding!