Download Project
This article describes how to show crystal report in ASP.net MVC.
Here I will describe two different ways for showing crystal report in MVC.
1. Showing crystal report using ASP.net web forms in MVC.
A. In same window
B. In different window
2. Showing crystal report from Controller/action (by generating PDF on fly).
A. In same window
B. In different window
Later I will describe how to create a generic/ common report viewer web form and generic/ common report viewer Controller class, which will be used for showing any Crystal report (with/ without data).
3. Creating Generic/Common report viewer
A. Create Generic Report Viewer Form for showing crystal report through asp.net (*.aspx) page
3.A.1. In same window
3.A.2. In different window
B. Create Generic Report Controller class for showing crystal report by pdf on fly.
3.B.1. In same window
3.B.2. In different window
1. Showing Crystal Report using ASP.net web forms in MVC
In this case we have to add an asp.net web form in our MVC project for showing crystal report. Consider this page name is aspnetsimple.aspx. This page will be called from controller. If we want to show report in different window then we have to call it from view using java script code (window.open(‘url’,..)).
Lets Create it..
1. Add an ASP.net web form in our MVC project and named it to aspnetsimple.aspx. (In my project under AspNetForms directory )
2. Add a CrystalReportViewer Control to it.
3. Add a Crystal Report (*.rpt) in our project and named it simple.rpt. (In my project under Rpts directory)
4. Now hookup simple.rpt with Crystal Report Viewer control (by writing following code on load event of aspnetsimple.aspx page)
protected void Page_Load(object sender, EventArgs e)
{
ReportDocument rd = new ReportDocument ();
rd.Load(Server.MapPath("~/Rpts/")+"simple.rpt");
CrystalReportViewer1.ReportSource = rd;
}
5. Now let’s create an empty controller named UsingWebFormControlles and generate Index view by right click on index action.
1.A Showing Simple Report from View In same window
6. Now create an action named show simple in UsingWebFormController for calling aspnetsimple.aspx page.
[HttpPost]
public void ShowSimple()
{
Response.Redirect("~/AspNetForms/aspnetsimple.aspx");
}
7. Now call this action from view to show simple report.
1.B Showing Simple Report from View In new window
8.If we want to show report in different window then we have to use java script. Here view contains following code
<script type="text/javascript">
function SimpleInNewWin() {
window.open("../AspNetForms/aspnetsimple.aspx");
}
</script>
<h2>Report Using ASP.net Web Forms</h2>
<h3>Simple Report</h3>
@using (Html.BeginForm("ShowSimple", "UsingWebForm"))
{
<input type="submit" value="Show simple" />
<input type="button" value="Show simple in New Window" onclick="SimpleInNewWin()"/>
<br />
}
This looks like following..

Now you are thinking how to you pass data or how to show report with data?? Don’t worry I will describe this on generic report section.
2. Showing crystal report from controller/action (by generating PDF on fly)
Here we will call an action from view which will generate report on fly and don’t use any *.aspx file.
Let’s start
>> Create a new controller named FromMvcController and generate index view.
>> Create an action named ShowSimple. This will show report on same window
2.A Showing report on same window.
Just need to call following action from view page. Then it will generate pdf on fly.
//Need to add following namespaces for using ExportFormatType and ReportClass
//using CrystalDecisions.CrystalReports.Engine;
//using CrystalDecisions.Shared;
public void ShowSimple()
{
using (ReportClass rptH = new ReportClass())
{
rptH.FileName = Server.MapPath("~/") + "//Rpts//simple.rpt";
rptH.Load();
rptH.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
}
}
2.B Opening report on new window.
For opening report on new window we have to use window.open and need to call above action from java script block. Consider following code for details.
<h2>Report from MVC</h2>
<script type="text/javascript">
function SimpleInNewWin() {
window.open("../FromMvc/ShowSimple");// calling action
}
</script>
<h2>Report Using ASP.net Web Forms</h2>
<h3>Simple Report</h3>
@using (Html.BeginForm("ShowSimple", "FromMvc"))
{
<input type="submit" value="Show simple" />
<input type="button" value="Show simple in New Window" onclick="SimpleInNewWin()"/>
<br />
}
3. Creating Generic/Common Report Viewer Form and Controller
A. Create Generic Report Viewer Form for showing crystal report through asp.net (*.aspx) page
B. Create Generic Report Controller class for showing crystal report by pdf on fly.
3. Generic/ common report viewer
In general report contains report source & parameter (from data and to date etc). Here I will create a generic/ common report viewer which will be used for showing different reports. Here I have to pass report name, parameter (if any) and report data source through session then it will generate report based on session data. In this way we don’t need to create separate report viewer page for each report. In my sample I have used four parameters for generating report.
Parameters:
1. Report Name
2. From Date
3. To Date
4. Report Source
Here sessions has used for passing data from action to generic report viewer.
3.A Creating Generic Report Viewer form for showing crystal report through asp.net (*.aspx) page
1. Let’s add a web page in our project under AspNetForms folder and named it aspnetgeneric.aspx.

2. Then add a Crystal Report Viewer control on it.
3. Then add following code on page load event
protected void Page_Load(object sender, EventArgs e)
{
try
{
bool isValid = true;
// Setting ReportName
string strReportName = System.Web.HttpContext.Current.Session["ReportName"].ToString();
// Setting FromDate
string strFromDate = System.Web.HttpContext.Current.Session["rptFromDate"].ToString();
// Setting ToDate
string strToDate = System.Web.HttpContext.Current.Session["rptToDate"].ToString();
// Setting Report Data Source
var rptSource = System.Web.HttpContext.Current.Session["rptSource"];
if (string.IsNullOrEmpty(strReportName)) // Checking is Report name provided or not
{
isValid = false;
}
if (isValid) // If Report Name provided then do other operation
{
ReportDocument rd = new ReportDocument();
string strRptPath = Server.MapPath("~/") + "Rpts//" + strReportName;
//Loading Report
rd.Load(strRptPath);
// Setting report data source
if (rptSource != null && rptSource.GetType().ToString() != "System.String")
rd.SetDataSource(rptSource);
if (!string.IsNullOrEmpty(strFromDate))
rd.SetParameterValue("fromDate", strFromDate);
if (!string.IsNullOrEmpty(strToDate))
rd.SetParameterValue("toDate", strFromDate);
CrystalReportViewer1.ReportSource = rd;
Session["ReportName"] = "";
Session["rptFromDate"] = "";
Session["rptToDate"] = "";
Session["rptSource"] = "";
}
else
{
Response.Write("Nothing found/ No report found"); }
}
catch (Exception ex) { Response.Write(ex.ToString()); } }
Now our generic report viewer is ready. Before using this page we have to fill four session value (Session["ReportName"], Session["rptFromDate"], Session["rptToDate"] Session["rptSource"]) otherwise it will show error. After setting session value we can call this page for showing report.
3.A.1 Showing Crystal Report through generic report viewer in same window
>> Create an action which will fill all session value and then call report viewer page. Consider following action.
[HttpPost]
public void ShowGenericReport(string txtFromDate, string txtToDate)
{
// Setting session for generating report
this.HttpContext.Session["ReportName"] = "generic.rpt";
this.HttpContext.Session["rptFromDate"] = txtFromDate;
this.HttpContext.Session["rptToDate"] = txtToDate;
this.HttpContext.Session["rptSource"] = GetStudents();
// Redirecting generic report viewer page from action
Response.Redirect("~/AspNetForms/aspnetgeneric.aspx");
}
>> Then call this action from view page.
3.A.2 Showing Crystal Report through generic report viewer in new window
>> Here we need to create an action which will set all session value and then report viewer is called from java script block.
>>> So first we have to set session value.
[HttpPost]
public void ShowGenericReportInNewWin(string FromDate, string ToDate)
{
this.HttpContext.Session["ReportName"] = "generic.rpt";
this.HttpContext.Session["rptFromDate"] = FromDate;
this.HttpContext.Session["rptToDate"] = ToDate;
this.HttpContext.Session["rptSource"] = GetStudents();
}
>>> Then we have to call generic report viewer page from java script so that it open in new window.
function GenericInNewWin() {
var oParam = { "FromDate": "", "ToDate": "" };
oParam.FromDate = $("#txtFromDate").val();
oParam.ToDate = $("#txtToDate").val();
$.ajax({
url: '../../UsingWebForm/ShowGenericReportInNewWin',
data: JSON.stringify(oParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function () {
//calling generic report viewer page
window.open("../AspNetForms/aspnetgeneric.aspx", 'mywindow', 'fullscreen=yes, scrollbars=auto');
}
});
3.B Create Generic Report Controller class for showing crystal report by pdf on fly.
Now we will describe how we can show crystal report in pdf from common controller/action . First we have to create generic controller “GenericReportViewer” for showing crystal report in PDF/ other formats. So we can show crystal report from view in two ways.
3.B.1 Showing Crystal Report in same window
3.B.2 Showing Crystal Report in new window
Let’s create GenericReportViewer controller like following
public class GenericReportViewerController : Controller
{
public ActionResult Index()
{
return View();
}
public void ShowGenericRpt()
{
try
{
bool isValid = true;
string strReportName = System.Web.HttpContext.Current.Session["ReportName"].ToString(); // Setting ReportName
string strFromDate = System.Web.HttpContext.Current.Session["rptFromDate"].ToString(); // Setting FromDate
string strToDate = System.Web.HttpContext.Current.Session["rptToDate"].ToString(); // Setting ToDate
var rptSource = System.Web.HttpContext.Current.Session["rptSource"];
if (string.IsNullOrEmpty(strReportName))
{
isValid = false;
}
if (isValid)
{
ReportDocument rd = new ReportDocument();
string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Rpts//" + strReportName;
rd.Load(strRptPath);
if (rptSource != null && rptSource.GetType().ToString() != "System.String")
rd.SetDataSource(rptSource);
if (!string.IsNullOrEmpty(strFromDate))
rd.SetParameterValue("fromDate", strFromDate);
if (!string.IsNullOrEmpty(strToDate))
rd.SetParameterValue("toDate", strFromDate);
rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
// Clear all sessions value
Session["ReportName"] = null;
Session["rptFromDate"] = null;
Session["rptToDate"] = null;
Session["rptSource"] = null;
}
else
{
Response.Write("Nothing Found; No Report name found");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
Like previous we have to set session value and then need to call action “ShowGenericRpt” from “GenericReportViewer”.
3.B.1 Showing Crystal Report in same window
Lets create a controller “FromMvc” and an action “ShowGeneric” which will call ShowGenericRpt from genericReport Controller. This will generate PDF report on fly.
/// This is used for showing Generic Report(with data and report parameter) in a same window
public ActionResult ShowGeneric(string txtFromDate, string txtToDate)
{
this.HttpContext.Session["ReportName"] = "generic.rpt";
this.HttpContext.Session["rptFromDate"] = txtFromDate;
this.HttpContext.Session["rptToDate"] = txtToDate;
this.HttpContext.Session["rptSource"] = GetStudents();
return RedirectToAction("ShowGenericRpt", "GenericReportViewer");
}
3.B.2 Showing Crystal Report in new window
Here we have to do two things Set session value and then call generic action from view using java script.
Setting session value from following action
/// This is used for preprocess report data and next generic report called from java script block
[HttpPost]
public void ShowGenericRptInNewWin(string FromDate, string ToDate)
{
this.HttpContext.Session["ReportName"] = "generic.rpt";
this.HttpContext.Session["rptFromDate"] = FromDate;
this.HttpContext.Session["rptToDate"] = ToDate;
this.HttpContext.Session["rptSource"] = GetStudents();
}
Then we have to call ShowGenericRpt action. Let’s consider following code block for calling both action together.
function GenericInNewWin() {
var oParam = { "FromDate": "", "ToDate": "" };
oParam.FromDate = $("#txtFromDate").val();
oParam.ToDate = $("#txtToDate").val();
$.ajax({
url: '../../FromMvc/ShowGenericRptInNewWin',
data: JSON.stringify(oParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function () {// Calling generic rpt viewer
window.open("../GenericReportViewer/ShowGenericRpt", 'mywindow', 'fullscreen=yes, scrollbars=auto');
}
});
