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 a 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 a database and table.

Create Database

USE [master]  
GO   
/****** Object: Database [CustomerDB] Script Date: 9/25/2016 3:14:16 AM ******/  
CREATE DATABASE [CustomerDB]  
CONTAINMENT = NONE  
ON PRIMARY   
(
    NAME = N'CustomerDB', 
    FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CustomerDB.mdf', 
    SIZE = 3072KB, 
    MAXSIZE = UNLIMITED, 
    FILEGROWTH = 1024KB
)  
LOG ON   
(
    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%
)  
GO  
ALTER DATABASE [CustomerDB] SET COMPATIBILITY_LEVEL = 110  
GO 
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
BEGIN  
    EXEC [CustomerDB].[dbo].[sp_fulltext_database] @action = 'enable'  
END  
GO    
ALTER DATABASE [CustomerDB] SET ANSI_NULL_DEFAULT OFF   
GO   
ALTER DATABASE [CustomerDB] SET ANSI_NULLS OFF   
GO    
ALTER DATABASE [CustomerDB] SET ANSI_PADDING OFF   
GO    
ALTER DATABASE [CustomerDB] SET ANSI_WARNINGS OFF   
GO   
ALTER DATABASE [CustomerDB] SET ARITHABORT OFF   
GO    
ALTER DATABASE [CustomerDB] SET AUTO_CLOSE OFF   
GO    
ALTER DATABASE [CustomerDB] SET AUTO_CREATE_STATISTICS ON   
GO   
ALTER DATABASE [CustomerDB] SET AUTO_SHRINK OFF   
GO   
ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS ON   
GO   
ALTER DATABASE [CustomerDB] SET CURSOR_CLOSE_ON_COMMIT OFF   
GO   
ALTER DATABASE [CustomerDB] SET CURSOR_DEFAULT GLOBAL   
GO   
ALTER DATABASE [CustomerDB] SET CONCAT_NULL_YIELDS_NULL OFF   
GO  
ALTER DATABASE [CustomerDB] SET NUMERIC_ROUNDABORT OFF   
GO  
ALTER DATABASE [CustomerDB] SET QUOTED_IDENTIFIER OFF   
GO   
ALTER DATABASE [CustomerDB] SET RECURSIVE_TRIGGERS OFF   
GO  
ALTER DATABASE [CustomerDB] SET DISABLE_BROKER   
GO    
ALTER DATABASE [CustomerDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
GO    
ALTER DATABASE [CustomerDB] SET DATE_CORRELATION_OPTIMIZATION OFF   
GO   
ALTER DATABASE [CustomerDB] SET TRUSTWORTHY OFF   
GO  
ALTER DATABASE [CustomerDB] SET ALLOW_SNAPSHOT_ISOLATION OFF   
GO   
ALTER DATABASE [CustomerDB] SET PARAMETERIZATION SIMPLE   
GO   
ALTER DATABASE [CustomerDB] SET READ_COMMITTED_SNAPSHOT OFF   
GO   
ALTER DATABASE [CustomerDB] SET HONOR_BROKER_PRIORITY OFF   
GO   
ALTER DATABASE [CustomerDB] SET RECOVERY SIMPLE   
GO    
ALTER DATABASE [CustomerDB] SET MULTI_USER   
GO    
ALTER DATABASE [CustomerDB] SET PAGE_VERIFY CHECKSUM   
GO    
ALTER DATABASE [CustomerDB] SET DB_CHAINING OFF   
GO    
ALTER DATABASE [CustomerDB] SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF)   
GO   
ALTER DATABASE [CustomerDB] SET TARGET_RECOVERY_TIME = 0 SECONDS   
GO   
ALTER DATABASE [CustomerDB] SET READ_WRITE   
GO

Create Table

USE [CustomerDB]  
GO   
/****** Object: Table [dbo].[Customers] Script Date: 9/25/2016 3:14:46 AM ******/  
SET ANSI_NULLS ON  
GO   
SET QUOTED_IDENTIFIER ON  
GO   
SET ANSI_PADDING ON  
GO   
CREATE TABLE [dbo].[Customers](  
    [CustomerID] [int] NOT NULL,  
      NULL,  
      NULL,  
    [CustomerZipCode] [int] NULL,  
    [CustomerCountry] [varchar](50) NULL,  
      NULL,  
    CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
    (  
        [CustomerID] ASC  
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]    
GO   
SET ANSI_PADDING OFF  
GO

After creating the table, you can add some records, as shown below for demo purposes.

Table

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.

 New Project

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

MVC template

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, and click Add > Add New Item.

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

ADO.NET

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

 EF Designer

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

 Server name

Next

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

Finally, we see that the EDMX model generates a Customer class.

EDMX model

Create Crystal Report

To do this, right-click on CrystalReports folder > Add > New Item > Select Reporting > CrystalReports.

Name your CrystalReport and click the Add button.

Report

Crystal Report

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

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

 Window

After clicking OK, our Crystal Report has been created with success.

The next step is to right-click on Database Fields > Database Expert.

Database

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

 Model

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

Report

Create a controller

Now, we are going to create a controller. Right-click on the controller's folder > Add > Controller> Select MVC 5 Controller – Empty > click Add.

Controller

Enter Controller name (‘CustomerController’).

CustomerController

CustomerController.cs

using CrystalDecisions.CrystalReports.Engine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CrystalReportMVC.Controllers
{
    public class CustomerController : Controller
    {
        private CustomerDBEntities context = new CustomerDBEntities(); // DbContext

        // GET: Customer
        public ActionResult Index()
        {
            var customerList = context.Customers.ToList();
            return View(customerList);
        }
        public ActionResult ExportCustomers()
        {
            List<Customer> allCustomer = context.Customers.ToList();

            ReportDocument rd = new ReportDocument();
            rd.Load(Path.Combine(Server.MapPath("~/CrystalReports"), "ReportCustomer.rpt"));
            rd.SetDataSource(allCustomer);
            Response.Buffer = false;
            Response.ClearContent();
            Response.ClearHeaders();
            Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            stream.Seek(0, SeekOrigin.Begin);
            return File(stream, "application/pdf", "CustomerList.pdf");
        }
    }
}

Here, I’m creating the Index() action which will select all data from the Customers table and the ExportCustomers() action that allow us exporting data to pdf format by using crystal report.

Adding View

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

Adding View

Index cshtml

@model IEnumerable<CrystalReportMVC.Customer>
@{
    ViewBag.Title = "Index";
}
<h2>Customers List</h2>
<p>
    @Html.ActionLink("Create New", "Create")

    <div><a href="@Url.Action("ExportCustomers")"> Report PDF </a></div>
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CustomerName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CustomerEmail)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CustomerZipCode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CustomerCountry)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CustomerCity)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerEmail)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerZipCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerCountry)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CustomerCity)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
                @Html.ActionLink("Details", "Details", new { id=item.CustomerID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })
            </td>
        </tr>
    }
</table>

Output

Customer list

Output


Similar Articles