Tuesday, November 8, 2016

How to generate and download Json file in MVC

In this article I am going to explain how to generate and download Json file in mvc.

How to generate and download Json file in MVC



Description:
I want to generate the Json file of table data and can download it. To implement this on button click I will save the Json file to folder and auto downloading of file will be start.

Implementation:

I have created a table Employees and insert some dummy record into it.

Id
int
Name
varchar(50)
Phone
int
Salary
int
Department
varchar(100)
ImagePath
varchar(MAX)
EmailId
varchar(100)

I am using AngularJs to display data.

Add controller
Add a controller to project.  Import the serialization namespace to convert data into Json.
using System.Web.Script.Serialization;

Complete Code of Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
using System.IO;
using System.Web.Script.Serialization;

namespace MVC_Project.Controllers
{
    public class DemoController : Controller
    {
        //
        // GET: /Demo/
        DemoEntities1 db = new DemoEntities1();
        public JsonResult GetEmployee()
        {
            var emp = db.Employees.ToList();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
               
        public ActionResult JsonExample()
        {
            return View();
        }
        [HttpPost]
        public ActionResult JsonExample(Employee empobj)
        {          
            var emplist = db.Employees.ToList();
            string empjson = new JavaScriptSerializer().Serialize(emplist);
            string path = Server.MapPath("~/json/");
            System.IO.File.WriteAllText(path + "empjson.json", empjson);
            //download Json file
            string fullpath = @"F:\filepath\empjson.json";
            byte[] fileBytes = System.IO.File.ReadAllBytes(fullpath);
            string fileName = "empjson.json";
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
            //return json file
            //return Json(emplist);
        }    

    }
}

Add view
Now add view for JsonExample action method.

Code of View:

@{
    ViewBag.Title = "Generate JSON file";
}
<style>
    .grid{width:900px;height:480px;}
</style>
<h2>Generate JSON file</h2>
<form name="myform" method="post">
    <div ng-app="mvcapp" ng-controller="DemoController">
        <div ui-grid="gridOptions" ui-grid-pagination class="grid"></div>
        <input type="submit" value=" Generate JSON file " class="btn-primary" />
    </div>
</form>

<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.js"></script>
<script src="http://ui-grid.info/release/ui-grid.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">

<script>
    var app = angular.module('mvcapp', ['ngTouch', 'ui.grid']);
    app.controller('DemoController', function ($scope, $http) {
        $scope.gridOptions = {
            infiniteScrollRowsFromEnd: 40,
            infiniteScrollUp: true,
            infiniteScrollDown: true,
            rowHeight:100,
            columnDefs: [
              { field: 'Name' },
              { field: 'Phone' },
              { field: 'Salary', },
              { field: 'Department' },
              { field: 'EmailId', cellTemplate: '<div>{{row.entity.EmailId}}</div><div ng-if="row.entity.EmailId == null" style="color:red">Email id not available</div>' },
              { field: 'ImagePath', cellTemplate: '<div ng-if="row.entity.ImagePath == null" style="color:red"><img src="images/image.jpg" width="120px"/></div><img ng-if="row.entity.ImagePath != null" width=\"145px\" src=\"{{grid.getCellValue(row, col)}}\">', enableFiltering: false, enableSorting: false }
              ] 
        };
        $http.get('/Demo/GetEmployee').success(function (data) {
            $scope.gridOptions.data = data;
        });
    });
</script>

Now build and run the project. Click on Generate Json file button to test it. 
  


No comments:

Post a Comment