Using Crystal Report With ASP.NET MVC 5

Introduction

In this post, we will learn how we can use Crystal Report Control in an MVC application.

Today, my requirement is to export data from database table in PDF format by using crystal report and Entity Framework.

Prerequisites

For this, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

SQL Database part

Here, you can find the scripts to create database and table.

Create Database

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object: Database [CustomerDB] Script Date: 9/25/2016 3:14:16 AM ******/  
  5. CREATE DATABASE [CustomerDB]  
  6. CONTAINMENT = NONE  
  7. ON PRIMARY   
  8. NAME = N'CustomerDB', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9. LOG ON   
  10. NAME = N'CustomerDB_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [CustomerDB] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [CustomerDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [CustomerDB] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [CustomerDB] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [CustomerDB] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [CustomerDB] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [CustomerDB] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [CustomerDB] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [CustomerDB] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [CustomerDB] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [CustomerDB] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [CustomerDB] SET CURSOR_DEFAULT GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [CustomerDB] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [CustomerDB] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [CustomerDB] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [CustomerDB] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [CustomerDB] SET DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [CustomerDB] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [CustomerDB] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [CustomerDB] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [CustomerDB] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [CustomerDB] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [CustomerDB] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [CustomerDB] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [CustomerDB] SET MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [CustomerDB] SET PAGE_VERIFY CHECKSUM   
  98. GO  
  99.   
  100. ALTER DATABASE [CustomerDB] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [CustomerDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [CustomerDB] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [CustomerDB] SET READ_WRITE   
  110. GO  
Create Table
  1. USE [CustomerDB]  
  2. GO  
  3.   
  4. /****** Object: Table [dbo].[Customers] Script Date: 9/25/2016 3:14:46 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Customers](  
  15. [CustomerID] [intNOT NULL,  
  16. [CustomerName] [varchar](50) NULL,  
  17. [CustomerEmail] [varchar](50) NULL,  
  18. [CustomerZipCode] [intNULL,  
  19. [CustomerCountry] [varchar](50) NULL,  
  20. [CustomerCity] [varchar](50) NULL,  
  21. CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
  22. (  
  23. [CustomerID] ASC  
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  25. ON [PRIMARY]  
  26.   
  27. GO  
  28.   
  29. SET ANSI_PADDING OFF  
  30. GO  
After creating the table, you can add some records, as shown below for demo purposes.



Create your MVC application

Open Visual Studio and select File. Click New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.



Now, new dialog will pop up for selecting the template. We are going choose MVC template and click OK button.



After creating our project, we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

For this, right click on the project name, click Add > Add New Item.

Dialog box will pop up, inside Visual C# select Data then ADO.NET Entity Data Model, and enter name for your Dbcontext model as DbContextCustomer, finally click Add.



At this stage, we are going to choose EF Designer from database as given below.



In this snapshot given below, we need to select your server name, then via dropdown list in connection to a database section, you should choose your database name, finally click OK button.





After clicking on Next button, the dialog Entity Data Model Wizard will pop up for choosing the object which we want to use. In this example we are going to choose Customers table and click Finish button.

Finally, we see that EDMX model generates Customer class.



Create Crystal Report

For doing this, right click on CrystalReports folder > Add > New Item > Select Reporting > CrystalReports.
Name your CrystalReport and click Add button.





Note - If Crystal Report Control does not exist in your VS 2015, you must install it from here CRforVS_13_0_16.exe.

Next, window will pop up as given below, in this example we are going to choose "As a Blank Report" option, and click OK.



After clicking OK, our Crystal Report has been created with success.
The next step is to right click on Database Fields > Database Expert…



Now, a new window will pop up as shown below. We need to select model which will be using to display data (in this case our model is Customer).



After clicking OK, we proceed to drag all fields to the report as shown below.



Create a controller

Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> selecting MVC 5 Controller – Empty > click Add.



Enter Controller name (‘CustomerController’).



CustomerController.cs
  1. using CrystalDecisions.CrystalReports.Engine;  
  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.   
  9. namespace CrystalReportMVC.Controllers  
  10. {  
  11.     public class CustomerController : Controller  
  12.     {  
  13.         //DbContext  
  14.         private CustomerDBEntities context = new CustomerDBEntities();  
  15.         // GET: Customer  
  16.         public ActionResult Index()  
  17.         {  
  18.             var customerList = context.Customers.ToList();  
  19.             return View(customerList);  
  20.         }  
  21.   
  22.   
  23.         public ActionResult ExportCustomers()  
  24.         {  
  25.             List<Customer> allCustomer = new List<Customer>();  
  26.             allCustomer = context.Customers.ToList();  
  27.   
  28.   
  29.             ReportDocument rd = new ReportDocument();  
  30.             rd.Load(Path.Combine(Server.MapPath("~/CrystalReports"), "ReportCustomer.rpt"));  
  31.   
  32.             rd.SetDataSource(allCustomer);  
  33.   
  34.             Response.Buffer = false;  
  35.             Response.ClearContent();  
  36.             Response.ClearHeaders();  
  37.   
  38.             
  39.                 Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);  
  40.                 stream.Seek(0, SeekOrigin.Begin);  
  41.                 return File(stream, "application/pdf""CustomerList.pdf");  
  42.         }  
  43.   
  44.     }  
  45. }  
Here, I’m creating Index() action which will select all data from Customers table and ExportCustomers() action that allow us exporting data to pdf format by using crystal report.

Adding View

In CustomerController. Just right click on Index() action, select Add View and dialog will pop up, write a name for your view, then via dropdown list select List as template and Customer as model class. Finally click Add.



Index cshtml
  1. @model IEnumerable<CrystalReportMVC.Customer>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Customers List</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11.   
  12.     <div><a href="@Url.Action("ExportCustomers")"> Report PDF </a></div>  
  13.   
  14. </p>  
  15. <table class="table">  
  16.     <tr>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.CustomerName)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.CustomerEmail)  
  22.         </th>  
  23.         <th>  
  24.             @Html.DisplayNameFor(model => model.CustomerZipCode)  
  25.         </th>  
  26.         <th>  
  27.             @Html.DisplayNameFor(model => model.CustomerCountry)  
  28.         </th>  
  29.         <th>  
  30.             @Html.DisplayNameFor(model => model.CustomerCity)  
  31.         </th>  
  32.         <th></th>  
  33.     </tr>  
  34.   
  35. @foreach (var item in Model) {  
  36.     <tr>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.CustomerName)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.CustomerEmail)  
  42.         </td>  
  43.         <td>  
  44.             @Html.DisplayFor(modelItem => item.CustomerZipCode)  
  45.         </td>  
  46.         <td>  
  47.             @Html.DisplayFor(modelItem => item.CustomerCountry)  
  48.         </td>  
  49.         <td>  
  50.             @Html.DisplayFor(modelItem => item.CustomerCity)  
  51.         </td>  
  52.         <td>  
  53.             @Html.ActionLink("Edit""Edit"new { id=item.CustomerID }) |  
  54.             @Html.ActionLink("Details""Details"new { id=item.CustomerID }) |  
  55.             @Html.ActionLink("Delete""Delete"new { id=item.CustomerID })  
  56.         </td>  
  57.     </tr>  
  58. }  
  59.   
  60. </table> 
Output

 


Up Next
    Ebook Download
    View all
    Learn
    View all