Using Crystal Report in ASP.net MVC and creating generic report viewer

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');
}
});

Finally our application looks like following.

Download Project

  • http://www.rapidsofttechnologies.com/asp.net-application-development.html Burton Taylor

    Crystal report is one of the important reports which is nicely explained in this article.

    • http://e-rains.com Hasibul

      Thanks for reading my post…

  • Vatiekimo

    I run this project localhost is Success!
    I Deploy this project to IIS,but it SimpleInNewWin show “404 – file or directory not found”.
    How can I solve it ?
    Thanks!

    • Vatiekimo

      FromMvcController.cs
      rptH.FileName = Server.MapPath(“~/”) + “//Rpts//simple.rpt”;
      ~~~~~~~~~~~~~~~~~
      How can i edit it?
      Thanks~

      • hasibul2363

         hi you can easily edit this by changing your report directory “Rpts” to another name.

        Here Rpts is Reports folder and simple.rpt is report name.

        • Vatiekimo

          Hello~
          I edit it to
          window.open(”);

          Beacause
          window.open(“@Url.Content(“~/FromMvc/ShowSimple”)”);
          ” or ‘ will error!

          Thanks~*^O^*

          • hasibul2363

            Sorry,
            for razor view we have to use @ and for aspx view we have to use <%

          • Fatineh

            i run u’re application and it’s give me this error

            Could not load file or assembly ‘CrystalDecisions.ReportAppServer.ClientDoc’ or one of its dependencies. An attempt was made to load a program with an incorrect format.” please help me to solve it.Tks 

          • hasibul2363
          • LY Rithy

            Hi . thank you for your information in this article.

            And I have a problem when I search data in generic report or zoom in/out not work. simple report work fine .

            I don’t know how to fixed it.

            Please help me.!!!

            Thank You so much….

          • Shahin Al Kabir

            Vai..I want to use Crystal report in MVC4 with Entirety fretwork…plz give me suggestion.

          • hasibul2363

            Check following section
            3.A.2 Showing Crystal Report through generic report viewer in new window

            There you will find GetStudents() method which is responsible for providing data.

            Inside this method you can access EF and can retrive data from DbContext and then pass them to Crystal Report as a report Datasource.

    • hasibul2363

      Thanks for reading my blog.
      use
      window.open(“@Url.Content(“~/FromMvc/ShowSimple”)”);
      instead of
      window.open(“../FromMvc/ShowSimple”);
      Hope it will solve the problem.

  • Fati_guess

    thank you very match

  • Fatineh

    i run u’re application and it’s give me this error “Could not load file or assembly ‘CrystalDecisions.ReportAppServer.ClientDoc’ or one of its dependencies. An attempt was made to load a program with an incorrect format.” please help me to solve it.Tks

  • Hasib

    U have explain the topics nicely. thanks for everything!!!

    • hasibul2363

      Thanks..

  • Pelikxz

    Hi, the data being shown is hardcoded.. can you help me how can i get data from the tables or datasets. I said that it is hardcoded because of

    return new List() { new Student(){StudentID=1,StudentName=”Hasibul”}, new Student(){StudentID=2,StudentName=”Tst”}

    I’m a newbie in MVC.. hoping for your immediate response.. thank you…

    • hasibul2363

      Thanks for reading my post.
      I thought u have ready DataTable or DataSet which is loaded from db.
      now consider following
      > In UsingWebFormController.cs file
      > You have method “ShowGenericReport”
      there i wrote
      this.HttpContext.Session["rptSource"] = GetStudents();

      Now if u have datatable or dataset then u can use that datatable to bind with CR in following way
      this.HttpContext.Session["rptSource"] = dt; // here it is ur data table which is loaded with data from db.

      Now come on second point (Crystal report design)
      >I have used my entity class Student to design report.
      if u have have datatable then you have to design Crystal report by connecting ur crystal report with database.

      If u are not clear or have any confusion let me know…..

      • Pelikxz

        thank you.. it works for the datatable.. but if I want to use dataset, how can I do it?

        tnx for your answer..

        • hasibul2363

          Glad to hear that datatable is working..
          Now consider dataSet

          if your report consist of multiple command or multiple table then you have to send dataset to report viewer form.

          Consider your report use two command or two table. when you add them on report you will find on DataBaseexpart window named command_1 and command_2 if u use command.

          If you use table then u will find them by tbale name.

          Now from your code you have to make dataset in such a way so that dataset table name similar with your reports table name.

          If u use command in CR
          ———————————-
          In your report u have command_1 and command_2
          then you have to rename the table name from ur dataset. i considered your dataset has two table then you have to rename it following way
          ds.Tables[0].TableName = “command_1″
          ds.Tables[1].TableName = “command_2″

          Then you have to send this dataset to report viewer in following way

          this.HttpContext.Session["rptSource"] = ds;

          If u use table in CR
          ———————————
          In your report u have Table1 and Table2then you have to rename the table name from ur dataset. i considered your dataset has two table then you have to rename it following wayds.Tables[0].TableName = “Table1″ds.Tables[1].TableName = “Table2″

          Then you have to send this dataset to report viewer in following way
          this.HttpContext.Session["rptSource"] = ds;
          if your report consist of single table/command then you dont need to use dataset.
          If not clear let me know.

          • pelikxz

            thank u for the immediate response..

            i will do what you said and i’ll let you know about what will happen..

            again, thank u for your support..

          • Muhammed

            Please make this more clear

        • Muhammed

          Please make it more clear..

  • Alessandro

    Como passo password para database access?

    • hasibul2363

      Can you use English please.

  • Alessandro

    Connecting the report in Access database with password.
    I’m using the script below, but is experiencing logon error.

    using (ReportClass rptH = new ReportClass())
    {

    rptH.FileName = Server.MapPath(“~/”) + “//Rpts//CrystalReport1.rpt”;
    rptH.Load();
    TableLogOnInfos crtablesLogoninfos = new TableLogOnInfos();
    TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
    ConnectionInfo crConnectionInfo = new ConnectionInfo();
    Tables CrTables;

    crConnectionInfo.ServerName = “MS Access”;
    crConnectionInfo.DatabaseName = “c:\Program Files (x86)\Aula\teste\Escolar.mdb”;
    crConnectionInfo.UserID = “Admin”;
    crConnectionInfo.Password = “123456″;

    CrTables = rptH.Database.Tables;
    foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
    {
    crtableLogoninfo = CrTable.LogOnInfo;
    crtableLogoninfo.ConnectionInfo = crConnectionInfo;
    CrTable.ApplyLogOnInfo(crtableLogoninfo);
    }

    rptH.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, “crReport”); <<– ERROR HERE!
    }

    • hasibul2363

      You don’t need to do so many things….
      1. Just remove password when u will design Crystal report.
      a.After finishing Crystal Report Design impose password to your access db
      2. Use following connection string to connect

      Sample Connection String
      string strServerMapPath = Server.MapPath(“~/”) ;
      string connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + strServerMapPath + “DB\MyDB1.mdb; Jet OLEDB:Database Password=123;”;

      I have created a sample with access db and password. You can check from following link.
      Access DB password is 123

      https://3srebq.bay.livefilestore.com/y1pQ0Ym_H3qmXKKz9C5qsavdTSG2EEGjGtldMH8jzxeoLx7zNU-nbdm410TB5i4TAlYATv8k_Gwpn9-9Y2kmloH-w/CrystalReportSampleWithPasswordProtectedAccessDB.zip?download&psid=1

      NB: I have used “AddCommand” in CR instead of table name. You have to give table name as you used in CR. In CR I have a command named “Command” that’s why my dt.TableName is Command.

      • Alessandro Reale

        Thank you.
        Thanks for the explanation and example!
        Obrigado, valeu pela ajuda!

  • asad

    good Article Haseeb !

  • Badhon

    Hi,
    I’m trying follow this article but not being able to render the report. The .aspx page is rendering but not the report, I don’t why?

  • Badhon

    Everything is working, Great article…Thanks a lot.

    • hasibul2363

      Great! is it working now? as you said it is not working..

  • Nalaka Deshan

    nicely explain this article.. can we implement this with MVC4.. please guide ..

    • hasibul2363

      yes we can… everything will be same for MVC 4.
      Thanks for reading my post.

  • Yan

    the report does not show for me :(

    • hasibul2363

      are u getting any error message?

      • Yan

        I don’t get any error :( . But The cystal report doesn’t display. It seem to be not loaded in aspnetsimple.aspx

      • Yan
        • hasibul2363

          Which version of Visual Studio and CR you are using.

          I have used VS2010 and Crystal Report 13.0.1

          • Yan

            I use VS 2010 and Crystal Report 13.0.5

            It work by the way: 2. Showing crystal report from Controller/action (by generating PDF on fly).

            but not with another one. (doesn’t display report viewer)

          • hasibul2363

            Press Ctrl+Shift+J in your browser to see the error
            Solution 1:
            ==============
            Copy “aspnet_client” folder from
            C:inetpubwwwroot
            And Paste it to your application directory

            Solution 2:
            ===============
            Go to
            C:WindowsMicrosoft.NETFramework64v4.0.30319
            Or
            C:WindowsMicrosoft.NETFrameworkv4.0.30319

            Check for “ASP.NETClientFiles” folder if not exist create it and then paste “crystalreportviewers13″ folder
            from C:inetpubwwwrootaspnet_clientsystem_web4_0_30319

            Hope it will work
            Or you can check my another post
            http://hasibulhaque.com/index.php/2012/bobj-is-undefined/

            Let me know are you able to done or not

          • Yan

            yes. It’s now working great by solution 1.

            Thanks you a lot!

            And I have question that what “aspnet_client” folder is?

          • hasibul2363

            Glad to hear it is working… Congratulations!!

            About aspnet_client:
            After installing Crystal report it puts aspnet_client folder on IIS root path. this folder is necessary for rendering crystal report viewer. in your CR viewer toolbar you see different icons like next page, print etc that icon and action will come from this folder.

          • Yan

            Thanks for all! Great man! ^^

  • M Ziauddin Tanvir

    You are awesome :)

    • hasibul2363

      Thanks.

  • Anil

    Hi Hasibul,
    I am using your reports part , i am not getting any error . The report is generated but data is not shown , simple two date are show , i am also debug the code all the data is came into rptsource but why it is doing like that ?

    I thought is there any problem in Rpts generic.rpt file .In may table 20 to 25 fields are there . please help me how i do it….

  • Anil

    Hi Hasibul ,
    I am using your Report . I am not getting any error but data is not shown to me in my report simple two date is displayed after debuging i saw that all data is fetched from table to rptSource . I am using MVC3 and in my table has 20 to 25 columns . I thought is there any problem in Rpts’s generic.rpt file . Please help me how i will do it ?

    • hasibul2363

      Only generic report or All report is not showing data?

      • Anil

        Thanks for Quick reply…
        No I am only using Mvc3 generic report in same window and new window .

        • hasibul2363

          Your problem is data is not shwoing right?
          > you can send me your sample project so that i can test.
          > Another thing what is your VS version and what is your OS version and bit?

          • Anil

            VS Version :- 2010

            OS :- Win 7 , 32-Bit

            Copy your Rpts file and paste in my Project

            View (ReportView.cshtml)
            ——————————–
            @{
            ViewBag.Title = “Index”;
            }

            $(document).ready(function () {
            $(“.dtp”).datepicker();
            });
            function GenericInNewWin() {
            var oParam = { “FromDate”: “”, “ToDate”: “” };
            oParam.FromDate = $(“#txtFromDate”).val();
            oParam.ToDate = $(“#txtToDate”).val();
            $.ajax({
            url: ‘@Url.Action(“ShowGenericRptInNewWin”,”Health”)’,
            data: JSON.stringify(oParam),
            type: ‘POST’,
            contentType: ‘application/json;’,
            dataType: ‘json’,
            success: function () {
            window.open(‘@Url.Action(“ShowGenericRpt”,”Health”)’, ‘mywindow’, ‘fullscreen=yes, scrollbars=auto’);
            }
            });
            }

            @using (Html.BeginForm(“ShowGeneric”, “Health”))
            {
            Generic Report(With Data and Report Parameter)
            From
            To

            }

            Controller (HealthController.cs)
            —————————————-

            private List GetBasics() //BasicInformationVm model class
            {
            var db = new Health_ProfileEntities();
            var data = (from p in db.Basic_Information
            select
            new
            {
            p.Weight,p.Name,p.Cell,p.Dob,p.Email,p.Fax,p.Gender,p.Height,p.SugarLevel,p.WebsiteUrl,p.InsuranceCompany,p.InsuranceNumber,p.CurrentOccupation,p.PastOccupation,p.OfficeNumber,p.BloodPressure,p.BloodType,p.SecurityNumber,p.ReferredBy,p.HomeAddress,p.SameBGCont1,p.SameBGCont2,p.SameBGCont3,p.HomePhone,p.Fb_Id
            });
            List lb = new List();
            foreach (var rptdata in data)
            {
            lb.Add(new BasicInformationVm()
            {
            Weight = rptdata.Weight.ToString(),Name = rptdata.Name,Cell = rptdata.Cell,Gender = rptdata.Gender,Home_Phone = rptdata.HomePhone,DOB = Convert.ToDateTime(rptdata.Dob),Address = rptdata.HomeAddress,Website = rptdata.WebsiteUrl,InsuranceCompany = rptdata.InsuranceCompany,InsuranceNumber = rptdata.InsuranceNumber,Height = rptdata.Height,Office_Phone = rptdata.OfficeNumber,RefferedBy = rptdata.ReferredBy,BloodPressure = rptdata.BloodPressure,BloodType = rptdata.BloodType,SameBGCont1 = rptdata.SameBGCont1,SameBGCont2 = rptdata.SameBGCont2,SameBGCont3 = rptdata.SameBGCont3,SecurityNo = rptdata.SecurityNumber,Current_Occupation = rptdata.CurrentOccupation,SugarLevel = rptdata.SugarLevel,Past_Occupation = rptdata.PastOccupation,Fb_Id = rptdata.Fb_Id,Email = rptdata.Email,Fax = rptdata.Fax
            });
            }
            return lb;
            }

            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"] = GetBasics();
            return RedirectToAction(“ShowGenericRpt”, “Health”);
            }

            [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"] =GetBasics();
            }

            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”, strToDate);
            rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, “Report”);
            // 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());
            }
            }

            If i manually store the value in a list without studentID and StudentName nothing is working .

          • hasibul2363

            i am not asking about code.. please upload your full project on skydrive or dropbox so that i can check.
            what is your Crystal Report Version?

          • Anil

            Crystal report Version : 13.0.2000.0

            Simple can you told me how you generate that generic.rpt file in MVC3

          • hasibul2363

            I’ve described(In my post) how i generated generic report. I dont know in which part your are not clear.

          • Anil

            Hi Hasibul ,
            Bcoz of you l have completed my report part . Thanks a lot…….

          • hasibul2363

            Congratulations!!!
            Glad to hear you have completed your reporting part.

          • Anil

            Hi Hasibul,

            I have one more problem , If i run the application in Localhost it is Ok , After hosting i got an exception like ” System.TypeInitializationException: The type initializer for ‘CrystalDecisions.CrystalReports.Engine.ReportDocument’ threw an exception. —> System.Security.SecurityException: That assembly does not allow partially trusted callers. at CrystalDecisions.CrystalReports.Engine.ReportDocument..cctor() — End of inner exception stack trace — at CrystalDecisions.CrystalReports.Engine.ReportDocument..ctor() at MvcApplication1.Controllers.HealthController.ShowGenericRpt() in F:bkp appMvcApplication1MvcApplication1ControllersHealthController.cs:line 165 ”

            Line no. 165 is (see the previosly posted code ) : ReportDocument rd = new ReportDocument();

      • Anil

        I am a fresher , Can u told me how i create .rpt file in MVC3 ?

  • Muhammed

    How do we take field from more than one table
    in mvc3 VS2012
    using your example

  • garmanetti

    Hi Hasibul, congratulations for your excelent post!
    Do you have an example with database as datasource?

    Thanks a lot!

  • Silua

    I tried with your exam and I had a error with ShowGeneric and this is it:
    System.NotSupportedException: DataSet does not support System.Nullable. at System.Data.DataColumn..ctor(String columnName, Type dataType, String expr, MappingType type) at System.Data.DataColumnCollection.Add(String columnName, Type type) at CrystalDecisions.CrystalReports.Engine.Table.BuildTableFromMemberInfos(ArrayList memberInfos, Boolean autoFlattenCurrentLevel, Int32 currentLevel, Int32 maximumLevels, String namePrefix, DataTable table) at CrystalDecisions.CrystalReports.Engine.Table.BuildTableFromEnumerable(IEnumerable collection, Type dataClassType, String tableName) at CrystalDecisions.CrystalReports.Engine.Table.EnumerableToDataSet(IEnumerable collection) at CrystalDecisions.CrystalReports.Engine.Table.WrapAndCacheDotNetObject(Object val, Type type, ISCRAdoNetDataSet& crAdoNetDataSet) at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type) at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type) at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(Object dataSet) at MvcApplication1.Controllers.GenericReportViewerController.ShowGenericRpt() in C:UsersAdminDesktopQLSTMvcApplication1ControllersGenericReportViewerController.cs:line 45

    So. What can i need to do for fix it?

  • Pingback: Returning a Crystal report as a PDF ActionResult in ASP.Net MVC | Mythical Man MothMythical Man Moth