How to update database with JavaScript/jQuery without refreshing page Asp .Net Mvc


In this post, we will discuss how to update the database using JavaScript/jQuery without refreshing the page in ASP.NET MVC. Let's consider a scenario where we aim to update the details of a Professor in the database via an AJAX call without causing a page refresh. Below is a comprehensive example illustrating the step-by-step solution.

Implement an action in the controller to handle the update request from the view page.

[HttpPost]
public IActionResult UpdateProfessor(Professor professor)
{
    // Update the professor in the database using Entity Framework or any other ORM like ADO .NET
    
    _context.Professors.Update(professor);
    _context.SaveChanges();
    
    // Return success message or updated professor object if needed
    return Json(new { success = true, message = "Professor updated successfully" });
}
JavaScript/jQuery Code: Use AJAX to send the updated professor data to the server without refreshing the page.
$('#updateBtn').click(function() {
    var professorId = $('#professorId').val();
    var firstName = $('#firstName').val();
    var lastName = $('#lastName').val();
    var email = $('#email').val();
    
    // Create a JSON object with professor data
    var professorData = {
        Id: professorId,
        FirstName: firstName,
        LastName: lastName,
        Email: email
    };
    
    // Sending AJAX POST request to the server
    $.ajax({
        url: '/Professor/UpdateProfessor',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(professorData),
        success: function(response) {
            // Handle success response
            if (response.success) {
                alert(response.message);
               
            } else {
                alert('Failed to update professor');
            }
        },
        error: function(xhr, status, error) {
          
            console.error(error);
            alert('An error occurred while updating professor');
        }
    });
});