Tuesday, 10 October 2017

Bulk Data Insertion in a Single Click in ASPMVC

INSERTING LIST OF RECORDS IN A SiNGLE CLICK


Managing a huge number of database records related to a particular entity is very difficult in today's modern applications. For example,one customer can purchase multiple types of items, so in this case case the customer is a single entity and the items he is purchasing are different entities having multiple records with dynamic entries where we don't know the count. So in this scenario it's very difficult to manage the database table structure, so this  article is related to Solve this issue -

So, let's learn step by step so beginners can also learn how to Insert Bulk Record in A Single Click

Step 1: Create an MVC Application.
Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. create a New ASPMVC4 Application Named "MVCApplication7"
  2. Go t File->New->Project->ASP.NET MVC4 Web Application .Then Provide the Project Name as you wish.After clicking, the following window will appear :
  1. As shown in the preceding screenshot, click on the Basic template, then click OK. This will create an empty MVC web application.
Step 2: Add The Reference of Dapper ORM into Project.

Now the next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
        Right click on Solution, find Manage NuGet Package manager and click on it.
  1. After as shown in the image and type in search box "dapper".
  2. Select Dapper as shown in the image.
  3. Choose the version of the dapper library and click on install button.


    After installing the Dapper library, it will be added into the References of our solution explorer of MVC application such as:


    Step 3: Create Model Class.
    Now let's create the model class named ProductModel.cs by right-clicking on model folder  and 
    also Create one More Class To Map Customers With  Ordered Product - EmployeeModel.cs

    Go to Solution Explorer -> Right Click on Models Folder ->Add -> Class ->Write the Name of class “ProductModel.cs”.
     Note: 
    It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without the folder name or in a separate class library.

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4.   
    5. namespace MVCApplication7.Models  
    6. {  
    7.     public class EmployeeModel  
    8.       { 
    9.         public int ID { getset; }  
    10.         public string Name { getset; }  
    11.         public int  Age { getset; }  
    12.         public List<ProductModel>Products { getset; }    
    13.     }  
    14.     public class ProductModel  
    15.     {  
    16.          public int ID{get;set;}
    17.          public string ProductName{get;set;}
    18.          public int ProductCost{ getset; }  

    19.     }  

    Step 4 : Create Controller.

    Now let us add the MVC 5 controller "HomeController"

    Go to Solution Explorer -> Right Click on Controllers Folder ->Add -> Controller  ->Write the Name of Controller “HomeController”.

    Note:
     The controller name must have the suffix as 'Controller' after specifying the name of controller. 
    Create Table and Stored procedure.

    Step 5 : Now before creating the views let us create the table name customers , CustomerProduct in database to store the order details:


    I hope you have created the same table structure as shown above. Now create the stored procedures to insert the order details as in the following code snippet:
    1-Here I am Creating AddCustomer Procedure to Add Customer Record in Customers Table

    1. Create procedure AddCustmer  
    2. (  
    3. @Name varchar(50),  
    4. @Age  int,
    5. @ID int =null output  
    6. as  
    7. Begin  
    8.   
    9. INSERT INTO [dbo].[Customers]  
    10.            (  
    11.              Name,Age  
    12.            )  
    13.      VALUES  
    14.            (  
    15.           @Name,  
    16.           @Age  
    17.            )
    18. set @ID=SCOPE_IDENTITY()  
    19. return @id
    20. End  

    2-Here I am Creating AddCustomer Procedure to Add Products  Record in  Customers Table

    1. Create procedure AddCustomerProduct  
    2. (  
    3. @Name varchar(50),  
    4. @Cost  int,
    5. @ID int =null  
    6. as  
    7. Begin  
    8.   
    9. INSERT INTO [dbo].[CustomerProduct]  
    10.            (  
    11.              ID,ProductName,ProductCost
    12.            )  
    13.      VALUES  
    14.            (  
    15.           @ID,
    16.           @Name,  
    17.           @Cost  
    18.            )
    19. End  


    Step 6: Create Repository class.
    Go to Solution Explorer -> Right Click on Models Folder ->Add -> Class ->Write the Name of Class “DataLayer”.

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Data.SqlClient;
    6. using System.Configuration;
    7. using Dapper;
    8. using System.Data;
    9. using System.Web.Mvc;

    10. namespace MvcApplication7.Models
    11. {
    12.     public class DataLayer
    13.     {
    14.         SqlConnection Con;  

    15.         public DataLayer()
    16.         {
    17.             Connectin();
    18.         }

    19.         private void Connectin()
    20.         {
    21. Con = new SqlConnection("Data Source=Dhananjay\SqlExpress;User Id=sa;Password=1;Initial Catalog=Dhananjay");
    22.             if (Con.State == System.Data.ConnectionState.Open)
    23.             {
    24.                 Con.Close();
    25.             }
    26.             Con.Open();
    27.         }

    28.         
    29. public bool AddCustomer(EmployeeModel E)
    30.         {
    31.             try
    32.             {
    33.                 DynamicParameters Parm = new DynamicParameters();
    34.                 Parm.Add("@Name", E.Name);
    35.                 Parm.Add("@Age", E.Age);
    36.                 Parm.Add("@id", dbType: DbType.Int32, direction: ParameterDirection.Output, size: 5215585);
    37.                 Con.Execute("AddCustmer", Parm, commandType: System.Data.CommandType.StoredProcedure);
    38.                 var ProductID = Parm.Get<Int32>("@id"); 
    39.                 foreach(var p in E.Products)
    40.                 {
    41.                     DynamicParameters Parm2 = new DynamicParameters();
    42.                     Parm2.Add("@ID", ProductID);
    43.                     Parm2.Add("@Name", p.ProductName);
    44.                     Parm2.Add("@Cost", p.ProductCost);
    45.                     Con.Execute("ADdCustomerProduct", Parm2, commandType: System.Data.CommandType.StoredProcedure);
    46.                 }
    47.                 return true;

    48.             }
    49.             catch (Exception c) { return false; }
    50.         }
    51. }
    52. }

    Step 7: Create Method into the HomeController.cs file.

    Now open the HomeController.cs and create the following action methods:

    1. using System.Collections.Generic;  
    2. using System.Web.Mvc;   
    3. using System;  
    4. using System.Linq;
    5. using System.Web;
    6. using MvcApplicatin7.Models;  
    7.   
    8. namespace MvcApplication7.Controllers  
    9. {  
    10.     public class CustomerController : Controller  
    11.     {  
    12.   
    13.         // GET: Customer  
    14.         public ActionResult AddProduct()
    15.         {  
    16.             return View();  
    17.         }  
    18.         [HttpPost]  
    19.         public ActionResult AddProduct(EmployeeModel E)  
    20.         {  
    21.            return View(new DataLayer().AddCustomer(E));
    22.         } 
    23.     }  
    24. }  
    Step 8 : Create view named AddProduct 

    1. @{
    2.     ViewBag.Title = "AddProduct";
    3. }

    4. <h2>AddProduct</h2>

    5. <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    6. <script>
    7.     $(document).ready(function () {
    8.         $('input[type="text"].num').bind('keydown', function (e) {
    9.             // Allow: backspace, delete, tab, escape, enter and .
    10.             if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
    11.                 // Allow: Ctrl+A
    12.                 (e.keyCode == 65 && e.ctrlKey === true) ||
    13.                 // Allow: Ctrl+C
    14.                 (e.keyCode == 67 && e.ctrlKey === true) ||
    15.                 // Allow: Ctrl+X
    16.                 (e.keyCode == 88 && e.ctrlKey === true) ||
    17.                 // Allow: home, end, left, right
    18.                 (e.keyCode >= 35 && e.keyCode <= 39)) {
    19.                 // let it happen, don't do anything
    20.                 return;
    21.             }
    22.             if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    23.                 e.preventDefault();
    24.             }

    25.         });
    26.     });
    27.         function AddMore() {
    28.             $("#Products tr:last").after('<tr det="Product"><td><input type="text"></td><td><input type="text"></td></tr>');
    29.         }
    30.         function Add() {
    31.             debugger;
    32.             var OrderedProducts = [];
    33.             var isOk = true;
    34.             $('#Products tr[det="Product"]').each(function () {
    35.                 var Product = $($(this).find('input[type="text"]')[0]).val();
    36.                 var Cost = parseFloat($($(this).find('input[type="text"]')[1]).val());
    37.                 OrderedProducts.push({
    38.                     ProductName: Product,
    39.                     ProductCost: parseInt(Cost),
    40.                 });
    41.             })
    42.             if (!isOk) {
    43.                 return;
    44.             }
    45. $('input[type^="text"]').each(function () {
    46.                 if ($(this).val() == '') {
    47.                     alert('Please Enter ' + $(this).parent().prev().text());
    48.                     $(this).focus();
    49.                     isOk = false;
    50.                     return false;
    51.                 }
    52.             });
    53.             if (!isOk) {
    54.                 return;
    55.             }
    56.             var Order =
    57.                     {
    58.                         PurchaseOrderNo: $('#txtPONo').val(),
    59.                         Name: $('#UName').val(),
    60.                         Age: $('#UAge').val(),
    61.                         Products: OrderedProducts
    62.                     };
    63.             debugger;
    64.             $.ajax({
    65.                 type: "POST",
    66.                 dataType: 'text',
    67.                 contentType: 'application/json; charset=utf-8',
    68.                 url: "/Home/AddProduct",
    69.                 data: JSON.stringify(Order),
    70.                 success: function (res) {
    71.                     if (res == "True") {
    72.                         alert('Information Saved Successfully!');
    73.                         window.location.reload();
    74.                     }
    75.                     else {
    76.                         alert('Some Error occurred!');
    77.                     }
    78.                 },
    79.                 error: function (xhr, textStatus, errorThrown) {
    80.                     alert('Some Error occurred!');
    81.                 }
    82.             });
    83.         }
    84. </script>
    85. <table>
    86.     <tr>
    87.         <td>Name</td>
    88.         <td><input type="text" id="UName" /></td>
    89.     </tr>
    90.     <tr>
    91.         <td>Age</td>
    92.         <td><input type="text" id="UAge" class="num" /></td>
    93.     </tr>
    94. </table>
    95. <table id="Products">
    96.     <tr>
    97.     <th>Product Name</th>
    98.     <th>Product Cost</th>
    99.         <th></th>
    100.     </tr>
    101.     <tr det="Product">
    102.         <td><input type="text" /></td>
    103.         <td><input type="text" class="num" /></td>
    104.     </tr>
    105. </table>
    106. <input type="button" onclick="AddMore()" value="Add" />
    107. <input type="button" value="Click" onclick="Add()" />


    Step 09: Now run the application