How To Import JSON Data In SQL Server Using MVC 5

Introduction

In this article. I will demonstrate how to import JSON data into SQL server using MVC 5 and entity framework. I will create a json file and upload it into FileUpload in project. I will also use jQuery datatable for searching, shorting and paging.

Step 1 

Open SQL Server 2014 and create a database table.
  1. CREATE TABLE [dbo].[Product](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Price] [money] NULL,  
  5.     [Quantity] [intNULL,  
  6.  CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11.   
  12. GO  

Step 2

Open Visual Studio 2015, click on New Project, and create an empty web application project.

ASP.NET

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK, as shown in the below screenshot.

ASP.NET

After clicking on OK one more window will appear; choose empty, check on MVC checkbox and click on OK, as shown below screenshot.

ASP.NET

After clicking OK, the project will be created with the name of ImportJSONData_Demo.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

ASP.NET

After clicking on New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name DBModels (this name is not mandatory you can give any name) and click on Add.

ASP.NET

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next. 

ASP.NET

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local, then enter dot (.). Choose your database and click on OK.

ASP.NET

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.

ASP.NET

After clicking on NEXT another window will appear. Choose database table name as shown in the below screenshot, then click on Finish.

ASP.NET
 
ASP.NET

 The Entity Framework will be added and the respective class gets generated under Models folder.

ASP.NET

The following class will be added.

  1. namespace ImportJSONData_Demo.Models  
  2. {  
  3. using System;  
  4. using System.Collections.Generic;  
  5.    public partial class Product  
  6.    {  
  7.       public int Id { get; set; }  
  8.       public string Name { get; set; }  
  9.       public Nullable<decimal> Price { get; set; }  
  10.       public Nullable<int> Quantity { get; set; }  
  11.    }  

 

Step 4

Right-click on Controllers folder, select Add, then choose Controller as shown in below screenshot.

ASP.NET

After clicking on the controller, a window will appear. Choose MVC5 Controller-Empty click on Add.

ASP.NET

After clicking on Add, another window will appear with DefaultController. Change the name to HomeController; then click on Add. HomeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of default just change Home, as shown in the below screenshot.

ASP.NET

Complete code for Controller 

  1. using MvcImportJSONData_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. using Newtonsoft.Json;  
  9.   
  10. namespace MvcImportJSONData_Demo.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.         [HttpGet]  
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.         public ActionResult GetData()  
  21.         {  
  22.             using (DBModel db = new DBModel())  
  23.             {  
  24.                 List<Product> productList= db.Products.ToList<Product>();  
  25.                 return Json(new { data = productList}, JsonRequestBehavior.AllowGet);  
  26.             }  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public ActionResult Upload(HttpPostedFileBase jsonFile)  
  31.         {  
  32.                 using (DBModel db = new DBModel())  
  33.                 {  
  34.                     if (!jsonFile.FileName.EndsWith(".json"))  
  35.                     {  
  36.                         ViewBag.Error = "Invalid file type(Only JSON file allowed)";  
  37.                     }  
  38.                     else  
  39.                     {  
  40.                         jsonFile.SaveAs(Server.MapPath("~/FileUpload/" + Path.GetFileName(jsonFile.FileName)));  
  41.                         StreamReader streamReader = new StreamReader(Server.MapPath("~/FileUpload/" + Path.GetFileName(jsonFile.FileName)));  
  42.                         string data = streamReader.ReadToEnd();  
  43.                         List<Product> products = JsonConvert.DeserializeObject<List<Product>>(data);  
  44.   
  45.                         products.ForEach(p =>  
  46.                         {  
  47.                             Product product = new Product()  
  48.                             {  
  49.                                 Name = p.Name,  
  50.                                 Price = p.Price,  
  51.                                 Quantity = p.Quantity  
  52.                             };  
  53.                             db.Products.Add(product);  
  54.                             db.SaveChanges();  
  55.                         });  
  56.                         ViewBag.Success = "File uploaded Successfully..";  
  57.                     }  
  58.                 }  
  59.             return View("Index");  
  60.         }  
  61.     }  
  62. }  
Step 5
 
Click on Tools select NuGet Package Manager then choose Manage NuGet Packages for Solution click on it
 
ASP.NET 

After that a window will appear choose Browse type NewtonsoftJson and install package in project. As shown.

ASP.NET
 
Step 6
 
Create a folder to upload the file with the name FileUpload.

Step 7

Right-click on index action method in the Controller. Add View window will appear with default index name unchecked (use a Layout page). Click on Add as shown in the below screenshot. The View will be added in the Views folder under Home folder with name index.

Screenshot for adding view

ASP.NET

Step 8

Design View with HTML, cshtml and bootstrap 4 classes.

Complete Index View code

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Index</title>  
  11.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  12.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  13.     <script src="~/scripts/bootstrap.min.js"></script>    
  14.     <link href="~/Content/dataTables.bootstrap4.min.css" rel="stylesheet" />  
  15.     <script src="~/scripts/jquery.dataTables.min.js"></script>  
  16.     <script src="~/scripts/dataTables.bootstrap4.min.js"></script>  
  17.     <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"></script>  
  18.    <style type="text/css">  
  19.        .error {  
  20.            color: red;  
  21.            display: inline-block;  
  22.            margin-bottom: -57px !important;  
  23.            width: 100%;  
  24.        }  
  25.    </style>  
  26.      <script type="text/javascript">  
  27.         $(document).ready(function () {  
  28.             $('form').validate({  
  29.                 rules: {  
  30.                     JSONFile: {  
  31.                         required: true  
  32.                     }   
  33.                 },  
  34.                 messages: {  
  35.                 JSONFile: "Choose file to upload",  
  36.                 }  
  37.             })  
  38.             $('#dataTable').DataTable({  
  39.                 "ajax": {  
  40.                     "url""/Home/GetData",  
  41.                     "type""GET",  
  42.                     "datatype""json"  
  43.                 },  
  44.                 "columns": [  
  45.                     { "data""Id" },  
  46.                     { "data""Name" },  
  47.                     { "data""Price" },  
  48.                     { "data""Quantity" }  
  49.                 ]  
  50.             });  
  51.         });  
  52.     </script>   
  53. </head>  
  54. <body>  
  55.     <div class="container py-5">  
  56.         @using (Html.BeginForm("Upload""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  57.         {  
  58.             <div class="row">  
  59.                 <div class="col-sm-1 col-md-6 col-xs-12">                    
  60.                     <h5 class="text-danger">@ViewBag.Error</h5>  
  61.                     <h5 class="text-success">@ViewBag.Success</h5>  
  62.                     <div class="form-group">  
  63.                         <label>Choose JSON File:</label>  
  64.                         <div class="input-group">  
  65.                             <div class="custom-file">  
  66.                                 <input id="JSONfile" name="JSONFile" type="file" class="custom-file-input"  />  
  67.                                 <label class="custom-file-label"></label>  
  68.                             </div>  
  69.                             <div class="input-group-append">  
  70.                                 <input type="submit" class="btn btn-outline-primary" value="Upload" />  
  71.                             </div>  
  72.                         </div>  
  73.                     </div>  
  74.                 </div>  
  75.             </div>  
  76.         }  
  77.         <table id="dataTable" class="table table-bordered table-striped">  
  78.             <thead>  
  79.                 <tr>  
  80.                     <th>ID</th>  
  81.                     <th>Name</th>  
  82.                     <th>Price</th>  
  83.                     <th>Quantity</th>  
  84.                 </tr>  
  85.             </thead>  
  86.         </table>    
  87.     </div>     
  88. </body>  
  89. </html>  

Step 9

Create a JSON file with the name as products.json.

  1. [  
  2.    {"name":"Mobile Phone","price":15000,"quantity":2},  
  3.    {"name":"Headphone","price":500,"quantity":2},  
  4.    {"name":"Mouse","price":450,"quantity":5},  
  5.    {"name":"Key Board","price":700,"quantity":3},  
  6.    {"name":"Speaker","price":1000,"quantity":2},  
  7.    {"name":"Monitor","price":5000,"quantity":1},  
  8.    {"name":"I3 Process","price":9000,"quantity":2},  
  9.    {"name":"Camera","price":600,"quantity":2},  
  10.    {"name":"Printer","price":5000,"quantity":2},  
  11.    {"name":"WiFi Router","price":1000,"quantity":2}  
  12. ]  

Step 9

Run Project by pressing Ctrl+F5.

Screenshot 1

ASP.NET

 Screenshot 2

ASP.NET 

Screenshot 3

ASP.NET
Screenshot 4 
ASP.NET
 Screenshot 5
 
ASP.NET

Screenshot 6

ASP.NET


Similar Articles