Inserting List of Records into Single SQL Column As XML File In ASP.NET MVC

Background

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 we can solve this problem by converting these types of lists into the XML files and later on we can store created XML files into a SQL table single column by defining column data types as XML.

So, lets learn step by step so beginners can also learn how to convert generic lists into the XML file in ASP.NET MVC.

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. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:

 

  1. As shown in the preceding screenshot, click on Empty template and check MVC option, 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:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "dapper".
  3. Select Dapper as shown into the image .
  4. Choose version of 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:
 

If you want to learn how to install correct Dapper library , watch my video tutorial usin the following link,
I hope you have followed the same steps and installed dapper library.

Step 3: Create Model Class.

Now let's create the model class named CustomerOrderModel.cs by right clicking on model folder as in the following screenshot:
 
 
 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.
CustomerOrderModel.cs class code snippet:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace ConvertGenericListIntoXMLInMVC.Models  
  6. {  
  7.     public class CustomerOrderModel  
  8.     {  
  9.         [Display(Name="Item Code")]  
  10.         public string ItemCode { getset; }  
  11.         [Display(Name = "Product Name")]  
  12.         public string ProductName { getset; }  
  13.         [Display(Name = "Quantity")]  
  14.         public Int16 Qty { getset; }  
  15.         public double Price { getset; }  
  16.         [Display(Name = "Total Amount")]  
  17.         public double TotalAmount { getset; }  
  18.     }  
  19.     public class CustomerOrder  
  20.     {  
  21.         //using CustomerorderModel class as generic list to add multiple orders in list   
  22.   
  23.         public List<CustomerOrderModel> OrderDetails { getset; }  
  24.   
  25.     }  

 Step 4 : Create Controller.

Now let us add the MVC 5 controller as in the following screenshot:
 
 
 After clicking on Add button it will show the window. Specify the Controller name as Customer with suffix Controller:

Note:
The controller name must have the suffix as 'Controller' after specifying the name of controller.

Step 5 : Create Table and Stored procedure.

Now before creating the views let us create the table name CustomerOrderDetails 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. Create procedure PlaceOrderDetails  
  2. (  
  3. @Customer_Name varchar(50),  
  4. @OrderDetails varchar(max)  
  5. )  
  6. as  
  7. Begin  
  8.   
  9. INSERT INTO [dbo].[CustomerOrderDetails]  
  10.            (  
  11.            Customer_Name  
  12.            ,OrderDetails  
  13.            )  
  14.      VALUES  
  15.            (  
  16.           @Customer_Name,  
  17.           @OrderDetails  
  18.              
  19.            )  
  20.   
  21. End 
 Run the above script in sql it will generates the stored procedure to insert the order details into database .

Step 6: Create Repository class.

Now create Repository folder and Add CustomerOrderRepo.cs class for database related operations. Now create method in CustomerOrderRepo.cs to get the output parameter value from stored procedure as in the following code snippet:
 
  1. public class CustomerOrderRepo  
  2.    {  
  3.        SqlConnection con;  
  4.        //To Handle connection related activities  
  5.        private void connection()  
  6.        {  
  7.            string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
  8.            con = new SqlConnection(constr);  
  9.        }  
  10.        //Place order details  
  11.        public void PlaceOrderDetails(CustomerOrder Order)  
  12.        {  
  13.   
  14.            //Converting List to XML using LINQ to XML  
  15.            XDocument OrderDetails = new XDocument(new XDeclaration("1.0""UTF - 8""yes"),  
  16.            new XElement("CustomerOrder",  
  17.            from OrderDet in Order.OrderDetails  
  18.            select new XElement("OrderDetails",  
  19.            new XElement("ItemCode", OrderDet.ItemCode),  
  20.            new XElement("ProductName", OrderDet.ProductName),  
  21.            new XElement("Qty", OrderDet.Qty),  
  22.            new XElement("Price", OrderDet.Price),  
  23.            new XElement("TotalAmount", OrderDet.TotalAmount))));  
  24.   
  25.            //Consider customer name we are getting from current login  
  26.            string CustomerName = "Vithal Wadje";  
  27.   
  28.   
  29.            DynamicParameters ObjParm = new DynamicParameters();  
  30.            ObjParm.Add("@Customer_Name", CustomerName);  
  31.            ObjParm.Add("@OrderDetails", OrderDetails.ToString());  
  32.            connection();  
  33.            con.Open();  
  34.            con.Execute("PlaceOrderDetails", ObjParm,commandType:CommandType.StoredProcedure);  
  35.            con.Close();  
  36.            
  37.   
  38.        }  
  39.    } 
Note
  1. In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
Step 7: Create Method into the CustomerController.cs file.

Now open the CustomerController.cs and create the following action methods:
  1. using System.Collections.Generic;  
  2. using System.Web.Mvc;  
  3. using InsertingListAsXML.Repository;  
  4. using System;  
  5. using InsertingListAsXML.Models;  
  6.   
  7. namespace InsertingListAsXML.Controllers  
  8. {  
  9.     public class CustomerController : Controller  
  10.     {  
  11.   
  12.         //Adding records into list ,you can populate this list from database.  
  13.         List<CustomerOrderModel> objOrder = new List<CustomerOrderModel>()  
  14.             {  
  15.  new CustomerOrderModel {ItemCode="MO12",ProductName="Mouse",Qty=1,Price=150.00,TotalAmount=150.00 },  
  16. new CustomerOrderModel {ItemCode="CO11",ProductName="Cable",Qty=2,Price=250.00,TotalAmount=500.00 },  
  17. new CustomerOrderModel {ItemCode="KO67",ProductName="KeyBoard",Qty=3,Price=500.00,TotalAmount=1500.00 },  
  18. new CustomerOrderModel {ItemCode="PO55",ProductName="PenDrive",Qty=1,Price=200.00,TotalAmount=200.00 }  
  19.             };  
  20.   
  21.         // GET: Customer  
  22.         public ActionResult PlaceOrderDetails()  
  23.         {  
  24.            
  25.             CustomerOrder ObjOrderDetails = new CustomerOrder();  
  26.             //Assigning list of records to CustomerOrder generic list   
  27.             ObjOrderDetails.OrderDetails = objOrder;  
  28.             return View(ObjOrderDetails);  
  29.         }  
  30.         [HttpPost]  
  31.         public ActionResult PlaceOrderDetails(CustomerOrder Order)  
  32.         {  
  33.             try  
  34.             {  
  35.                 CustomerOrderRepo objOrder = new CustomerOrderRepo();  
  36.   
  37.                 objOrder.PlaceOrderDetails(Order);  
  38.   
  39.                 ViewBag.OrderStatus = "Your order placed successfully.";  
  40.             }  
  41.             catch (Exception)  
  42.             {  
  43.   
  44.                 ViewBag.OrderStatus= "Problem while processing order.";  
  45.             }  
  46.             CustomerOrder ObjOrderDetails = new CustomerOrder();  
  47.             //Assigning list of records to CustomerOrder generic list   
  48.             ObjOrderDetails.OrderDetails = objOrder;  
  49.             return View(ObjOrderDetails);  
  50.   
  51.         }  
  52.   
  53.     }  

 Step 8 : Create strongly typed view named PlaceOrderDetails using CustomerOrder.cs class .

Right click on View folder of created application and choose add view , select CustomerOrder class and scaffolding List template to create view as
 
 

Click on Add button then it will create the view named PlaceOrderdetails. Now open the PlaceOrderdetails.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,

PlaceOrderdetails.cshtml 
  1. @model ConvertGenericListIntoXMLInMVC.Models.CustomerOrder  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6.   
  7. <h3>Place Order Details</h3>  
  8. <hr />  
  9. @using (Html.BeginForm("PlaceOrderDetails""Customer"))  
  10. {  
  11.     <div class="form-horizontal">  
  12.         <div class="form-group">  
  13.             <div class="col-md-12">  
  14.                 <table class="table table-condensed table-hover">  
  15.                     <tr>  
  16.                         <th>  
  17.                             Item Code  
  18.                         </th>  
  19.                         <th>  
  20.                             Product Name  
  21.                         </th>  
  22.                         <th>  
  23.                             Quantity  
  24.                         </th>  
  25.                         <th>  
  26.                             Price  
  27.                         </th>  
  28.                         <th>  
  29.                             Total Amount  
  30.                         </th>  
  31.                     </tr>  
  32.                     @{  
  33.                         if (Model.OrderDetails.ToList()!=null)  
  34.                         {  
  35.   
  36.                         
  37.                         int i = 0;  
  38.                         foreach (var item in Model.OrderDetails.ToList())  
  39.                         {  
  40.   
  41.                             <tr>  
  42.                                 <td>  
  43.   
  44.   
  45.                                     @Html.EditorFor(o => o.OrderDetails[i].ItemCode, new { @id = "ItemCode_" + i })  
  46.                                 </td>  
  47.                                 <td>  
  48.                                     @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })  
  49.                                 </td>  
  50.                                 <td>  
  51.                                     @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })  
  52.                                 </td>  
  53.                                 <td>  
  54.                                     @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_" + i })  
  55.                                 </td>  
  56.                                 <td>  
  57.                                     @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_" + i })  
  58.                                 </td>  
  59.   
  60.                             </tr>  
  61.                                 i++;  
  62.                             }  
  63.                         }  
  64.                     }  
  65.                 </table>  
  66.             </div>  
  67.         </div>  
  68.         <hr />  
  69.         <div class="form-group">  
  70.             <div class="col-md-12 text-center">  
  71.                 <input type="submit" value="Order Now" class="btn btn-primary" />  
  72.             </div>  
  73.         </div>  
  74.   
  75.         <div class="form-group">  
  76.             <div class="col-md-12 text-center text-success" >  
  77.                @ViewBag.OrderStatus  
  78.             </div>  
  79.         </div>  
  80.   
  81.   
  82.     </div>  
  83.  } 
After adding model, view , controller and Repository folder our final solution explorer will look like as follows,
 
 
 Now we have done all coding to upload files .

Step 9 : Now run the application.

After running the application the initial screen will look like as follows,
 
 
In the preceding table consider we are adding orders (records) dynamically. Now click on Order Now button and after successfully inserting order into database the following message will appears as
 
 

Now after clicking on Order Now button the records get stored into the SQL table as XML file  which we have created to store the order details as XML file .
 
In the preceding table you have seen that OrderDetail XML file is stored into the SQL column named OrderDetails . Now Double click on XML file which is highlighted like hyperlink into the SQL table column then XML file records will be shown as follows
 
 
I hope from all the preceding examples we have learned how to Insert List of Records into single SQL column as XML file in ASP.NET MVC

Note:
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • Configure the database connection in the web.config file depending on your database server location.
Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET: