Convert Generic List Into XML In ASP.NET MVC

Background

Sometimes we need to work with very complex type dynamic data where data gets stored into the generic list. 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 entry 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 file and later on we can store created XML file into single table and SQL column by defining column data type 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:


Step 2: Create Model Class

Now let us create the model class file named CustomerModel.cs by right clicking on model folder as in the following screenshot:



Note: 

It is not mandatory that Model class should be in Models 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 name or without folder name or in a separate class library.

CustomerModel.cs class file 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     
  22.         //multiple orders in list    
  23.         public List<CustomerorderModel> OrderDetails { getset; }    
  24.     
  25.     }    
  26. }    
Step 3: Add Controller Class.

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 be having suffix as 'Controller' after specifying the name of controller. Now modify the default code in CustomerController.cs class file to convert generic list to XML, after modifying code will look like as follows,

CustomerController.cs
  1. using System.Collections.Generic;    
  2. using System.Linq;    
  3. using System.Web.Mvc;    
  4. using ConvertGenericListIntoXMLInMVC.Models;    
  5. using System.Xml.Linq;    
  6.     
  7. namespace ConvertGenericListIntoXMLInMVC.Controllers    
  8. {    
  9.     public class CustomerController : Controller    
  10.     {    
  11.         // GET: Customer    
  12.         public ActionResult AddOrderDetails()    
  13.         {    
  14.             //Adding records into list ,you can populate this list from database.    
  15.             List<CustomerorderModel> objOrder = new List<CustomerorderModel>()    
  16.             {    
  17.  new CustomerorderModel {ItemCode="MO12",ProductName="Mouse",Qty=1,Price=150.00,TotalAmount=150.00 },    
  18. new CustomerorderModel {ItemCode="CO11",ProductName="Cable",Qty=2,Price=250.00,TotalAmount=500.00 },    
  19. new CustomerorderModel {ItemCode="KO67",ProductName="KeyBoard",Qty=3,Price=500.00,TotalAmount=1500.00 },    
  20. new CustomerorderModel {ItemCode="PO55",ProductName="PenDrive",Qty=1,Price=200.00,TotalAmount=200.00 }    
  21.             };    
  22.     
  23.             CustomerOrder ObjOrderDetails = new CustomerOrder();    
  24.             //Assigning list of records to CustomerOrder    
  25.             //generic list     
  26.             ObjOrderDetails.OrderDetails = objOrder;    
  27.             return View(ObjOrderDetails);    
  28.         }    
  29.         [HttpPost]    
  30.         public ActionResult AddOrderDetails(CustomerOrder Order)    
  31.         {    
  32.             //Converting List to XML using LINQ to XML    
  33.             // the xml doc will get stored into OrderDetails object of XDocument    
  34.             XDocument OrderDetails = new XDocument(new XDeclaration("1.0""UTF - 8""yes"),    
  35.             new XElement("CustomerOrder",    
  36.             from OrderDet in Order.OrderDetails    
  37.             select new XElement("OrderDetails",    
  38.             new XElement("ItemCode", OrderDet.ItemCode),    
  39.             new XElement("ProductName", OrderDet.ProductName),    
  40.             new XElement("Qty", OrderDet.Qty),    
  41.             new XElement("Price", OrderDet.Price),    
  42.             new XElement("TotalAmount", OrderDet.TotalAmount))));    
  43.             return View();    
  44.         }    
  45.            
  46.     }    
  47. }   
Step 4:

Creating strongly typed view named AddOrderDetails using CustomerOrder model. Right click on View folder of created application and choose add view, select CustomerOrder model class and scaffolding List template as,



Click on Add button then it will create the view named AddOrderDetails, Now open the AddOrderDetails .cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like as in the following,

AddOrderDetails .cshtml
  1. @model ConvertGenericListIntoXMLInMVC.Models.CustomerOrder    
  2. @{    
  3.     ViewBag.Title = "www.compilemode.com";    
  4. }    
  5. <h4>Order Details</h4>    
  6. <hr />    
  7. @using (Html.BeginForm("AddOrderDetails""Customer"))    
  8. {    
  9.     <div class="form-horizontal">    
  10.         <div class="form-group">    
  11.             <div class="col-md-12">    
  12.                 <table class="table table-condensed table-hover">    
  13.                     <tr>    
  14.                         <th>    
  15.                             Item Code    
  16.                         </th>    
  17.                         <th>    
  18.                             Product Name    
  19.                         </th>    
  20.                         <th>    
  21.                             Quantity    
  22.                         </th>    
  23.                         <th>    
  24.                            Price    
  25.                         </th>    
  26.                         <th>    
  27.                             Total Amount    
  28.                         </th>                         
  29.                     </tr>    
  30.                    @{    
  31.                        int i = 0;    
  32.                        foreach (var item in Model.OrderDetails.ToList())    
  33.                        {    
  34.                                                       
  35.                         <tr>    
  36.                             <td>    
  37.                                   
  38.                                 
  39.                                 @Html.EditorFor(o => o.OrderDetails[i].ItemCode, new { @id = "ItemCode_" + i })    
  40.                             </td>    
  41.                             <td>    
  42.                                 @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })    
  43.                             </td>    
  44.                             <td>    
  45.                                 @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })    
  46.                             </td>    
  47.                             <td>    
  48.                                 @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_"+i })    
  49.                             </td>    
  50.                             <td>    
  51.                                 @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_"+i })    
  52.                             </td>    
  53.     
  54.                         </tr>    
  55.                         i++;    
  56.                        }    
  57.                 }    
  58.                 </table>    
  59.             </div>    
  60.         </div>    
  61.         <hr />    
  62.         <div class="form-group">    
  63.             <div class="col-md-offset-2 col-md-10 text-center">    
  64.                 <input type="submit" value="Order Now" class="btn btn-primary" />    
  65.             </div>    
  66.         </div>        
  67.     </div>    
  68. }   
Now after adding the Model, View and controller into our project. The solution explorer will look like as follows,



Now we have done all coding to upload files .

Step 5 :
Now run the application. After running the application initial screen will look like as follows,


In preceding table we are adding orders (records) dynamically. Put break point on AddOrderDetails action result method and click on Order Now button. Now after executing the LINQ to XML code, click on Text Visualizer of XDocument object OrderDetails, It will show the following XML code which is generated by using LINQ to XML method as,



I hope from all the preceding examples we have learned how to convert generic lists into XML 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.
Summary

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

Read more articles on ASP.NET:


Similar Articles