Inserting List of Records into Single SQL Column As XML File In ASP.NET MVC
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, let's 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:
- create a New ASPMVC4 Application Named "ConvertGenericListIntoXMLInMVC"
- 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 :
- 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:
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.
- After as shown in the image and type in search box "dapper".
- Select Dapper as shown in the image.
- 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 CustomerOrderModel.cs by right-clicking on model folder
Now let's create the model class named CustomerOrderModel.cs by right-clicking on model folder
Go to Solution Explorer -> Right Click on Models Folder ->Add -> Class ->Write the Name of class “CustomerOrderModel.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.
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:
- 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 4 : Create Controller.
Now let us add the MVC 5 controller "CustomerController"
Now let us add the MVC 5 controller "CustomerController"
Go to Solution Explorer -> Right Click on Controllers Folder ->Add -> Controller ->Write the Name of Controller “CustomerController”.
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 CustomerOrderDetails in database to store the order details:
Step 5 : 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:
- Create procedure PlaceOrderDetails
- (
- @Customer_Name varchar(50),
- @OrderDetails varchar(max)
- )
- as
- Begin
- INSERT INTO [dbo].[CustomerOrderDetails]
- (
- Customer_Name
- ,OrderDetails
- )
- VALUES
- (
- @Customer_Name,
- @OrderDetails
- )
- End
Step 6: Create Repository class.
Now Add CustomerOrderRepo.cs class for database related operations in Models Folder .
Now Add CustomerOrderRepo.cs class for database related operations in Models Folder .
- public class CustomerOrderRepo
- {
- SqlConnection con;
- //To Handle connection related activities
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
- con = new SqlConnection(constr);
- }
- //Place order details
- public void PlaceOrderDetails(CustomerOrder Order)
- {
- //Converting List to XML using LINQ to XML
- 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))));
- //Consider customer name we are getting from current login
- string CustomerName = "Dhananjay Shukla";
- DynamicParameters ObjParm = new DynamicParameters();
- ObjParm.Add("@Customer_Name", CustomerName);
- ObjParm.Add("@OrderDetails", OrderDetails.ToString());
- connection();
- con.Open();
- con.Execute("PlaceOrderDetails", ObjParm,commandType:CommandType.StoredProcedure);
- con.Close();
- }
- }
Note
Now open the CustomerController.cs and create the following action methods:
- 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.
Now open the CustomerController.cs and create the following action methods:
- using System.Collections.Generic;
- using System.Web.Mvc;
- using InsertingListAsXML.Repository;
- using System;
- using InsertingListAsXML.Models;
- namespace InsertingListAsXML.Controllers
- {
- public class CustomerController : Controller
- {
- //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 }
- };
- // GET: Customer
- public ActionResult PlaceOrderDetails()
- {
- CustomerOrder ObjOrderDetails = new CustomerOrder();
- //Assigning list of records to CustomerOrder generic list
- ObjOrderDetails.OrderDetails = objOrder;
- return View(ObjOrderDetails);
- }
- [HttpPost]
- public ActionResult PlaceOrderDetails(CustomerOrder Order)
- {
- try
- {
- CustomerOrderRepo objOrder = new CustomerOrderRepo();
- objOrder.PlaceOrderDetails(Order);
- ViewBag.OrderStatus = "Your order placed successfully.";
- }
- catch (Exception)
- {
- ViewBag.OrderStatus= "Problem while processing order.";
- }
- CustomerOrder ObjOrderDetails = new CustomerOrder();
- //Assigning list of records to CustomerOrder generic list
- ObjOrderDetails.OrderDetails = objOrder;
- return View(ObjOrderDetails);
- }
- }
- }
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
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
- @model ConvertGenericListIntoXMLInMVC.Models.CustomerOrder
- @{
- ViewBag.Title = "www.compilemode.com";
- }
- <h3>Place Order Details</h3>
- <hr />
- @using (Html.BeginForm("PlaceOrderDetails", "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>
- @{
- if (Model.OrderDetails.ToList()!=null)
- {
- 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-12 text-center">
- <input type="submit" value="Order Now" class="btn btn-primary" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-12 text-center text-success" >
- @ViewBag.OrderStatus
- </div>
- </div>
- </div>
- }
Step 9 : Add Connection String in Web.config File:
<add name="SqlConn" connectionString="Data Source=DHANANJAY/SQLExpress;User Id=sa;Password=1;Initial Catalog=Demo" providerName="System.Data.SqlClient" />
Now we have done all coding to upload files .
Step 10 : Now run the application.
After running the application the initial screen will look like as follows,
Step 10 : Now run the application.
After running the application the initial screen will look like as follows,
useful
ReplyDeleteNice Job
ReplyDelete