Saturday, August 10, 2019

How to insert multiple row to database using asp.net MVC

Step - 1: Create New Project.


Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for save data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one table as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Apply Validation On Model.

Open your model and add validation. Please follow below code

  1. namespace MVCAjaxSave
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. public partial class ContactInfo
  7. {
  8. public int ID { get; set; }
  9. [Required(ErrorMessage = "Contact Name required!", AllowEmptyStrings = false)]
  10. public string ContactName { get; set; }
  11. [Required(ErrorMessage = "Contact No required!", AllowEmptyStrings = false)]
  12. public string ContactNo { get; set; }
  13. }
  14. }

Step-6: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for save data.

Here I have added "BulkData" Action into "Save" Controller. Please write this following code

  1. public ActionResult BulkData()
  2. {
  3. // This is only for show by default one row for insert data to the database
  4. List<ContactInfo> ci = new List<ContactInfo> {new ContactInfo{ ID = 0, ContactName = "", ContactNo=""} };
  5. return View(ci);
  6. }

Step-8: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
[N:B:Please Rebuild solution before add view.] 

Step-9: Add jquery code for save data to the server.

Jquery Code 
  1. @section Scripts{
  2. @Scripts.Render("~/bundles/jqueryval")
  3. <script language="javascript">
  4. $(document).ready(function () {
  5.  
  6. //1. Add new row
  7. $("#addNew").click(function (e) {
  8. e.preventDefault();
  9. var $tableBody = $("#dataTable");
  10. var $trLast = $tableBody.find("tr:last");
  11. var $trNew = $trLast.clone();
  12.  
  13. var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
  14. $trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
  15. $.each($trNew.find(':input'), function (i, val) {
  16. // Replaced Name
  17. var oldN = $(this).attr('name');
  18. var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
  19. $(this).attr('name', newN);
  20. //Replaced value
  21. var type = $(this).attr('type');
  22. if (type.toLowerCase() == "text") {
  23. $(this).attr('value', '');
  24. }
  25.  
  26. // If you have another Type then replace with default value
  27. $(this).removeClass("input-validation-error");
  28.  
  29. });
  30. $trLast.after($trNew);
  31.  
  32. // Re-assign Validation
  33. var form = $("form")
  34. .removeData("validator")
  35. .removeData("unobtrusiveValidation");
  36. $.validator.unobtrusive.parse(form);
  37. });
  38.  
  39. // 2. Remove
  40. $('a.remove').live("click", function (e) {
  41. e.preventDefault();
  42. $(this).parent().parent().remove();
  43. });
  44.  
  45. });
  46. </script>
  47. }
Complete View 
  1. @model List<MVCBulkInsert.ContactInfo>
  2. @{
  3. ViewBag.Title = "Insert Bulk Data";
  4. }
  5. <style>
  6. td {
  7. padding:5px;
  8. }
  9. </style>
  10. <div style="width:700px; padding:5px; background-color:white;">
  11. @using (Html.BeginForm("BulkData","Save", FormMethod.Post))
  12. {
  13. @Html.AntiForgeryToken()
  14. @Html.ValidationSummary(true)
  15. if (ViewBag.Message != null)
  16. {
  17. <div style="border:solid 1px green">
  18. @ViewBag.Message
  19. </div>
  20. }
  21. <div><a href="#" id="addNew">Add New</a></div>
  22. <table id="dataTable" border="0" cellpadding="0" cellspacing="0">
  23. <tr>
  24. <th>Contact Name</th>
  25. <th>Contact No</th>
  26. <th></th>
  27. </tr>
  28. @if (Model != null && Model.Count > 0)
  29. {
  30. int j = 0;
  31. foreach (var i in Model)
  32. {
  33. <tr style="border:1px solid black">
  34. <td>@Html.TextBoxFor(a=>a[j].ContactName)</td>
  35. <td>@Html.TextBoxFor(a=>a[j].ContactNo)</td>
  36. <td>
  37. @if (j > 0)
  38. {
  39. <a href="#" class="remove">Remove</a>
  40. }
  41. </td>
  42. </tr>
  43. j++;
  44. }
  45. }
  46. </table>
  47. <input type="submit" value="Save Bulk Data" />
  48. }
  49. </div>
  50.  
  51. @* Here I will add Jquery Code for validation / dynamically add new rows / Remove rows etc *@
  52.  
  53. @section Scripts{
  54. @Scripts.Render("~/bundles/jqueryval")
  55. <script language="javascript">
  56. $(document).ready(function () {
  57.  
  58. //1. Add new row
  59. $("#addNew").click(function (e) {
  60. e.preventDefault();
  61. var $tableBody = $("#dataTable");
  62. var $trLast = $tableBody.find("tr:last");
  63. var $trNew = $trLast.clone();
  64.  
  65. var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
  66. $trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
  67. $.each($trNew.find(':input'), function (i, val) {
  68. // Replaced Name
  69. var oldN = $(this).attr('name');
  70. var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
  71. $(this).attr('name', newN);
  72. //Replaced value
  73. var type = $(this).attr('type');
  74. if (type.toLowerCase() == "text") {
  75. $(this).attr('value', '');
  76. }
  77.  
  78. // If you have another Type then replace with default value
  79. $(this).removeClass("input-validation-error");
  80.  
  81. });
  82. $trLast.after($trNew);
  83.  
  84. // Re-assign Validation
  85. var form = $("form")
  86. .removeData("validator")
  87. .removeData("unobtrusiveValidation");
  88. $.validator.unobtrusive.parse(form);
  89. });
  90.  
  91. // 2. Remove
  92. $('a.remove').live("click", function (e) {
  93. e.preventDefault();
  94. $(this).parent().parent().remove();
  95. });
  96.  
  97. });
  98. </script>
  99. }

Step-10: Add another action into your controller for Save Data to the server.

Here I have added "BulkData" Action into "Save" Controller for POST Action. Please write this following code

  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult BulkData(List<ContactInfo> ci)
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  8. {
  9. foreach (var i in ci)
  10. {
  11. dc.ContactInfoes.Add(i);
  12. }
  13. dc.SaveChanges();
  14. ViewBag.Message = "Data successfully saved!";
  15. ModelState.Clear();
  16. ci = new List<ContactInfo> { new ContactInfo{ ID = 0, ContactName = "", ContactNo= ""} };
  17. }
  18. }
  19. return View(ci);
  20. }
Step-11: Run Application.

1 comment:

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...