, ,

Autosave form after 5 seconds using MVC platform – C#

Posted by

To implement an auto-save functionality in an MVC application using C#, you can use JavaScript along with AJAX requests to periodically save the form data on the server. Here’s an example:

  1. In your View (.cshtml file), add the following JavaScript code to handle the auto-save functionality:
    $(document).ready(function() {
        var timer; // Timer variable

        // Bind change event to form fields
        $('form input, form textarea').on('input', function() {
            clearTimeout(timer); // Clear previous timer
            timer = setTimeout(saveForm, 5000); // Start new timer for auto-saving after 5 seconds

        // Function to save the form data
        function saveForm() {
            var formData = $('form').serialize(); // Serialize the form data

                url: '@Url.Action("SaveForm", "YourController")', // Replace with your controller and action method names
                type: 'POST',
                data: formData,
                success: function(response) {
                    console.log('Form saved successfully!');
                error: function(xhr, status, error) {
                    console.log('Error occurred while saving the form.');
  1. In your Controller, add the following action method to handle the form data saving:
public class YourController : Controller
    // Other action methods...

    public ActionResult SaveForm(YourModel model)
        // Implement code to save the form data to the database or perform any necessary actions

        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
  1. Customize the SaveForm action method to suit your requirements. You can save the form data to the database, update records, or perform any other necessary actions.
  2. Replace “YourController” with the actual name of your controller and “YourModel” with the name of your model class.
  3. Make sure to include the necessary JavaScript libraries (e.g., jQuery) in your View for the auto-save functionality to work.

With this code, whenever a change occurs in any input field or textarea within the form, a timer is started. If no changes occur within 5 seconds, the saveForm function is triggered, which sends an AJAX request to the specified controller action method to save the form data on the server.

Note: This code is a basic example and may require adjustments based on your specific application structure and requirements.