Sometimes we have a requirement in which we need to manage information without touching the database, and save all of that information only when the user clicks the SUBMIT button, i.e. in one store one client wants to buy some products, the cashier has to scan every product and the system will be listing the items on screen, but the information will be submitted only when the cashier clicks the "MAKE TRANSACTION" button.
So here is a small tutorial of how to add items to a temportal/virtual table (html table in front end), and remove items from that table just using jquery, and saving all items of the table into database only when the submit button is clicked:
So, let's begin with the tutorial.
The tools we need for this tutorial:
  1. EntityFramework.
  2. Jquery.
  3. Bootstrap (Optional)
  4. Visual Studio
  5. Sql Server Management Studio
First of all let's create a new database and a new table, open sql server management studio, and execute the following scripts,
Create database MoviesDB
  1. create database MoviesDB -- Create a new database with the name MoviesDB
  2. use MoviesDB -- use this database
  3. --Create new Movie table
  4. Create Table Movie (
  5. Id int Identity primary key,
  6. Title varchar(500),
  7. Summary varchar(max),
  8. Year int
  9. )
Now let's create a new MVC Project:
Open Visual Studio, then go to File - New - Project, and under Web section select .Net web application, give it any name you want and click OK button:
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Now in the project, right click on references and then Manage nuget packages, click on browse tab and then type Entity Framework :
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Install the package (select the most recent version).
Now lets create the database model for Movie Table using code first method (manually):
Add a new class with the name "Movie" inside the Models folder:
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Here is the definition of the class,
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations.Schema;
  4. using System.Linq;
  5. using System.Web;
  6. namespace CrudJQuery.Models
  7. {
  8. [Table("Movie")] //Attribute required to prevent pluralization(Movies)
  9. public class Movie
  10. {
  11. public int Id { get; set; }
  12. public string Title { get; set; }
  13. public string Summary { get; set; }
  14. public int Year { get; set; }
  15. }
  16. }
Now we need to create our dbcontext class to use this model. To do this let's create a new folder in the project and name it "DBModels", once created add a new class named "MoviesContext" to it,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Here is the definition of the class,
  1. using CrudJQuery.Models;
  2. using Microsoft.EntityFrameworkCore;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data.Entity;
  6. using System.Linq;
  7. using System.Web;
  8. namespace CrudJQuery.DBModels
  9. {
  10. public class MoviesContext : DbContext
  11. {
  12. public MoviesContext() : base("DbConnection") //Connection string name located in web.config file
  13. {
  14. }
  15. public DbSet<Movie> Movies { get; set; } //Movie model as property
  16. }
  17. }
The last step to configure entity framework is to add the connection string in our web.config file.
Open your web.config file located on the root path of the project and then add the following content inside configuration node.
  1. <connectionStrings>
  2. <add name="DbConnection" connectionString="Data Source=JASBALANCE; Initial Catalog=MoviesDB; Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
Here we are doing connection to sql server through Windows authentication:
The name of the connection string must match the one specified in our context class.
Now let's create a new function to receive the list of movies from the frontend and to save the informaiton into our database, open HomeController,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
And replace all content for the following content,
  1. using CrudJQuery.DBModels;
  2. using CrudJQuery.Models;
  3. using System.Collections.Generic;
  4. using System.Web.Mvc;
  5. namespace CrudJQuery.Controllers //namespace will depend of your project name
  6. {
  7. public class HomeController : Controller
  8. {
  9. public ActionResult Index()
  10. {
  11. return View();
  12. }
  13. [HttpPost]
  14. public JsonResult SaveMovies(List<Movie> Movies) //function to save information into database
  15. {
  16. using (MoviesContext db = new MoviesContext())
  17. {
  18. foreach (Movie mov in Movies)
  19. {
  20. db.Movies.Add(mov);
  21. }
  22. db.SaveChanges();
  23. }
  24. bool Result = true;
  25. return Json(Result);
  26. }
  27. }
  28. }
Now we are done with the backend side.
Let's continue with the front end stuff.
Open Layout file located on Views/Shared folder and replace all content by the following content , here we are including reference to jquery and bootstrap.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>JQUERY Crud</title>
  5. @*Bootstrap reference*@
  6. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
  7. integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  8. @*Jquery Reference*@
  9. <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  10. </head>
  11. <body>
  12. <div class="container body-content">
  13. @RenderBody()
  14. <hr />
  15. </div>
  16. @RenderSection("scripts", required: false)
  17. </body>
  18. </html>
Now open Index.cshtml file located inside views folder and replace all of its content with the following content,
  1. @*Page scripts references*@
  2. <script src="~/JsJquery/MoviesScript.js" type="text/javascript"></script>
  3. <section class="m-3">
  4. <section class="card">
  5. <section class="card-header text-center">
  6. <label class="h3">Create Movies</label>
  7. </section>
  8. <section class="card-body">
  9. <section id="form-container">
  10. <section class="form-group">
  11. <label>Title:</label>
  12. <input type="text" placeholder="Title" id="TitleTxt" class="form-control" />
  13. </section>
  14. <section class="form-group">
  15. <label>Summary:</label>
  16. <input type="text" placeholder="Summary" id="SummaryTxt" class="form-control" />
  17. </section>
  18. <section class="form-group">
  19. <label>Year:</label>
  20. <input type="text" placeholder="Year" id="YearTxt" class="form-control" />
  21. </section>
  22. <section class="text-center">
  23. <a href="javascript:void(0)" class="text-info" id="AddTempMovieBtn">ADD MOVIE</a>
  24. </section>
  25. </section>
  26. <section id="MsnContainer">
  27. <section class="text-center">
  28. <label class="font-weight-bold text-danger" id="Msn"></label>
  29. </section>
  30. </section>
  31. <br><br>
  32. <section id="table-container">
  33. <table class="table table-bordered table-striped" id="table-information">
  34. <thead>
  35. <tr class="bg-info text-light font-weight-bold text-center">
  36. <td>Title</td>
  37. <td>Summary</td>
  38. <td>Year</td>
  39. <td>Actions</td>
  40. </tr>
  41. </thead>
  42. <tbody id="table-body"></tbody>
  43. </table>
  44. <section class="text-center">
  45. <button id="SubmitMoviesBtn" disabled="disabled" class="btn btn-success w-50">SAVE ALL MOVIES</button>
  46. </section>
  47. </section>
  48. </section>
  49. </section>
  50. </section>
And to finish let's create a new folder in our project and name it "JsJquery", then add a new javascript file inside this folder and name it "MoviesScript" (this is the file referenced in Index view file and this file contains all js operations to control that view):
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Now paste all the following content on it (please read comments to see what each method/function does),
  1. $(document).ready(function () {
  2. //set onclick events for buttons
  3. $('#AddTempMovieBtn').click(function () { AddTempMoview(); });
  4. $('#SubmitMoviesBtn').click(function () { PostMovies(); });
  5. });
  6. //Send List of Movies to controller
  7. function PostMovies() {
  8. //Build List object that has to be sent to controller
  9. var MoviesList = []; // list object
  10. $('#table-information > tbody > tr').each(function () { //loop in table list
  11. var Movie = {}; // create new Movie object and set its properties
  12. Movie.Title = this.cells[0].innerHTML;
  13. Movie.Summary = this.cells[1].innerHTML;
  14. Movie.Year = this.cells[2].innerHTML;
  15. MoviesList.push(Movie); // add Movie object to list object
  16. });
  17. //Send list of movies to controller via ajax
  18. $.ajax({
  19. url: '/home/SaveMovies',
  20. type: "POST",
  21. data: JSON.stringify(MoviesList),
  22. contentType: "application/json",
  23. dataType: "json",
  24. success: function (response) {
  25. // Process response from controller
  26. if (response === true) {
  27. ShowMsn("Movies have been saved successfully."); // show success notification
  28. ClearForm(); //clear form fields
  29. $('#table-body').empty(); // clear table items
  30. CheckSubmitBtn(); // disable submit button
  31. } else {
  32. ShowMsn("Ooops, an error has ocurrer while processing the transaction.");
  33. }
  34. }
  35. });
  36. }
  37. //Add item to temp table
  38. function AddTempMoview() {
  39. //Create Movie Object
  40. var Movie = {};
  41. Movie.Title = $('#TitleTxt').val();
  42. Movie.Summary = $('#SummaryTxt').val();
  43. Movie.Year = $('#YearTxt').val();
  44. //Validate required fields
  45. var Errors = ""; // Main Error Messages Variable
  46. //validate Title
  47. if (Movie.Title.trim().length == 0) {
  48. Errors += "Title is required.<br>";
  49. $('#TitleTxt').addClass("border-danger");
  50. } else {
  51. $('#TitleTxt').removeClass("border-danger");
  52. }
  53. //validate Summary
  54. if (Movie.Summary.trim().length == 0) {
  55. Errors += "Please provide a summary.<br>";
  56. $('#SummaryTxt').addClass("border-danger");
  57. } else {
  58. $('#SummaryTxt').removeClass("border-danger");
  59. }
  60. //validate Year
  61. if (Movie.Year.trim().length < 4) {
  62. Errors += "A valid Year is required.<br>";
  63. $('#YearTxt').addClass("border-danger");
  64. } else {
  65. $('#YearTxt').removeClass("border-danger");
  66. }
  67. if (Errors.length > 0) {//if errors detected then notify user and cancel transaction
  68. ShowMsn(Errors);
  69. return false; //exit function
  70. }
  71. //end validation required
  72. //Validate no duplicated Titles
  73. var ExistTitle = false; // < -- Main indicator
  74. $('#table-information > tbody > tr').each(function () {
  75. var Title = $(this).find('.TitleCol').text(); // get text of current row by class selector
  76. if (Movie.Title.toLowerCase() == Title.toLowerCase()) { //Compare provided and existing title
  77. ExistTitle = true;
  78. return false;
  79. }
  80. });
  81. //Add movie if title is not duplicated otherwise show error
  82. if (ExistTitle === false) {
  83. ClearMsn();
  84. //Create Row element with provided data
  85. var Row = $('<tr>');
  86. $('<td>').html(Movie.Title).addClass("TitleCol").appendTo(Row);
  87. $('<td>').html(Movie.Summary).appendTo(Row);
  88. $('<td>').html(Movie.Year).appendTo(Row);
  89. $('<td>').html("<div class='text-center'><button class='btn btn-danger btn-sm' onclick='Delete($(this))'>Remove</button></div>").appendTo(Row);
  90. //Append row to table's body
  91. $('#table-body').append(Row);
  92. CheckSubmitBtn(); // Enable submit button
  93. }
  94. else {
  95. ShowMsn("Title can not be duplicated.");
  96. }
  97. }
  98. // clear all textboxes inside form
  99. function ClearForm() {
  100. $('#form-container input[type="text"]').val('');
  101. }
  102. //Msn label for notifications
  103. function ShowMsn(message) {
  104. $('#Msn').html(message);
  105. }
  106. //Clear text of Msn label
  107. function ClearMsn() {
  108. $('#Msn').html("");
  109. }
  110. //Delete selected row
  111. function Delete(row) { // remove row from table
  112. row.closest('tr').remove();
  113. CheckSubmitBtn();
  114. }
  115. //Enable or disabled submit button
  116. function CheckSubmitBtn() {
  117. if ($('#table-information > tbody > tr').length > 0) { // count items in table if at least 1 item is found then enable button
  118. $('#SubmitMoviesBtn').removeAttr("disabled");
  119. } else {
  120. $('#SubmitMoviesBtn').attr("disabled", "disabled");
  121. }
  122. }
And we are done, now let's see the project in action. Run your project and you will see the following page,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
SAVE ALL MOVIES button will be enable only if one or more items are added in the table, so let's add 3 or more items,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
To remove a movie from the table just click the remove button of the movie you want to remove.
Finally, to save those movies into the db just click SAVE ALL MOVIES button and jquery will execute our function to send the list of movies to the controller,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
and let's check our database,
Manage Temp HTML Table With jQuery, And Post List Of Items To Database Using MVC And EF
And that's it my friends, I hope this post helps someone. Thanks.