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 in a 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 the created XML file into a single table and SQL column by defining column data type as XML.

So, let's learn step by step so beginners can also learn how to convert generic lists into XML files in ASP.NET MVC.

Step 1. Create an MVC Application.

Now let us start with a step-by-step approach to 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:
    Microsoft

Step 2. Create Model Class

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

CustomerModel

Note. It is not mandatory that Model class should be in the 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 names or without folder names 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 a 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.

Add

After clicking on Add button it will show the window. Specify the Controller name as Customer with the suffix Controller.

Note. The controller name must be having suffix as 'Controller' after specifying the name of controller. Now modify the default code in the CustomerController.cs class file to convert the generic list to XML, after code will look 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 a strongly typed view named AddOrderDetails using the CustomerOrder model. Right-click on the View folder of the created application and choose to add view, select CustomerOrder model class and scaffolding List template as.

CustomerOrder

Click on the 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 the MVC scaffolding template, Now modify the default code to make it 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 to our project. The solution explorer will look as follows.

 Solution explorer

Now we have done all coding to upload files.

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

Application

In the preceding table, we are adding orders (records) dynamically. Put a breakpoint on the AddOrderDetails action result method and click on the 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.

 XML code

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