Convert Complex Model Generic List Into XML In ASP.NET MVC

Sometimes we need to work with very complex type dynamic data where data get stored into the generic list. For example, one customer can purchase multiple types of item, so in this case case customer is single entity and the items he is purchasing is different entity having multiple records with dynamic entry where we don't know the count, So in this scenario its very difficult to manage the database table structure so we can solve this problem by converting these type of list 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 list 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:
    using System;    
    using System.Collections.Generic;    
    using System.ComponentModel.DataAnnotations;    
        
    namespace ConvertGenericListIntoXMLInMVC.Models    
    {    
        public class CustomerorderModel    
        {    
            [Display(Name="Item Code")]    
            public string ItemCode { get; set; }    
            [Display(Name = "Product Name")]    
            public string ProductName { get; set; }    
            [Display(Name = "Quantity")]    
            public Int16 Qty { get; set; }    
            public double Price { get; set; }    
            [Display(Name = "Total Amount")]    
            public double TotalAmount { get; set; }    
        }    
        public class CustomerOrder    
        {    
            //using CustomerorderModel class as generic list to add     
            //multiple orders in list    
            public List<CustomerorderModel> OrderDetails { get; set; }    
        
        }    
    }    
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
    using System.Collections.Generic;    
    using System.Linq;    
    using System.Web.Mvc;    
    using ConvertGenericListIntoXMLInMVC.Models;    
    using System.Xml.Linq;    
        
    namespace ConvertGenericListIntoXMLInMVC.Controllers    
    {    
        public class CustomerController : Controller    
        {    
            // GET: Customer    
            public ActionResult AddOrderDetails()    
            {    
                //Adding records into list ,you can populate this list from database.    
                List<CustomerorderModel> objOrder = new List<CustomerorderModel>()    
                {    
     new CustomerorderModel {ItemCode="MO12",ProductName="Mouse",Qty=1,Price=150.00,TotalAmount=150.00 },    
    new CustomerorderModel {ItemCode="CO11",ProductName="Cable",Qty=2,Price=250.00,TotalAmount=500.00 },    
    new CustomerorderModel {ItemCode="KO67",ProductName="KeyBoard",Qty=3,Price=500.00,TotalAmount=1500.00 },    
    new CustomerorderModel {ItemCode="PO55",ProductName="PenDrive",Qty=1,Price=200.00,TotalAmount=200.00 }    
                };    
        
                CustomerOrder ObjOrderDetails = new CustomerOrder();    
                //Assigning list of records to CustomerOrder    
                //generic list     
                ObjOrderDetails.OrderDetails = objOrder;    
                return View(ObjOrderDetails);    
            }    
            [HttpPost]    
            public ActionResult AddOrderDetails(CustomerOrder Order)    
            {    
                //Converting List to XML using LINQ to XML    
                // the xml doc will get stored into OrderDetails object of XDocument    
                XDocument OrderDetails = new XDocument(new XDeclaration("1.0", "UTF - 8", "yes"),    
                new XElement("CustomerOrder",    
                from OrderDet in Order.OrderDetails    
                select new XElement("OrderDetails",    
                new XElement("ItemCode", OrderDet.ItemCode),    
                new XElement("ProductName", OrderDet.ProductName),    
                new XElement("Qty", OrderDet.Qty),    
                new XElement("Price", OrderDet.Price),    
                new XElement("TotalAmount", OrderDet.TotalAmount))));    
                return View();    
            }    
               
        }    
    }   
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

    @model ConvertGenericListIntoXMLInMVC.Models.CustomerOrder    
    @{    
        ViewBag.Title = "www.compilemode.com";    
    }    
    <h4>Order Details</h4>    
    <hr />    
    @using (Html.BeginForm("AddOrderDetails", "Customer"))    
    {    
        <div class="form-horizontal">    
            <div class="form-group">    
                <div class="col-md-12">    
                    <table class="table table-condensed table-hover">    
                        <tr>    
                            <th>    
                                Item Code    
                            </th>    
                            <th>    
                                Product Name    
                            </th>    
                            <th>    
                                Quantity    
                            </th>    
                            <th>    
                               Price    
                            </th>    
                            <th>    
                                Total Amount    
                            </th>                         
                        </tr>    
                       @{    
                           int i = 0;    
                           foreach (var item in Model.OrderDetails.ToList())    
                           {    
                                                          
                            <tr>    
                                <td>    
                                      
                                    
                                    @Html.EditorFor(o => o.OrderDetails[i].ItemCode, new { @id = "ItemCode_" + i })    
                                </td>    
                                <td>    
                                    @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })    
                                </td>    
                                <td>    
                                    @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })    
                                </td>    
                                <td>    
                                    @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_"+i })    
                                </td>    
                                <td>    
                                    @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_"+i })    
                                </td>    
        
                            </tr>    
                            i++;    
                           }    
                    }    
                    </table>    
                </div>    
            </div>    
            <hr />    
            <div class="form-group">    
                <div class="col-md-offset-2 col-md-10 text-center">    
                    <input type="submit" value="Order Now" class="btn btn-primary" />    
                </div>    
            </div>        
        </div>    
    }   
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 preceding examples we have learned how to convert generic list into XML in ASP.NET MVC.

Note:
  • 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:

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode