Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 & SSRS ReportViewer - How to Implement?

I have spent hours trying to solve this and so far I can find MVC1, MVC2, and MVC3 based solutions but nothing about MVC5 and using SSRS and ReportViewer. Frankly, I don't know WebForms, since I joined the programming world after MVC was a big thing in the shop I work at. Enough extra backstory, I'll get to it.

I have:

  • Written a stored procedure
  • Used the Business Intelligence Tools in VS 2013 to design my report
  • Viewed the report in the designer and know it's good
  • Attempted to integrate the ReportViewer into my application without success
  • Determined it appears I need to re-execute my query call (despite it being in the report design), and written code to do this, using a set of test dates
  • Determined WebForms is somehow involved in getting my report to display in my application.

So I've reached the point where I think I just need the aspx file to do what I need to do. If anyone can look this over and help me out, you'll cure me of many hours of stress.

First, a snippet of my RouteConfig.cs file:

routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

My Reporting Controller Code:

     [HttpPost]
        public ActionResult GetSysWideQuizReport([Bind(Include = "Topic, Date1, Date2")] QuizReporting quizParams)
        {
 ReportViewer ReportViewer1 = new ReportViewer();
            ReportViewer1.ProcessingMode = ProcessingMode.Local;
            ReportViewer1.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Reports\System Quiz Report.rdl";
            ReportDataSource source = new ReportDataSource("DataSet1", QuizData(quizParams));
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(source);

            return View(ReportViewer1);
        }



private DataTable QuizData(QuizReporting quizParams)
        {

            DataSet ds = new DataSet("DataSet1");

                using(SqlConnection connection = new SqlConnection())
                { 

                connection.ConnectionString = GetConnectionString();

                SqlCommand cmd = new SqlCommand("SystemQuizReport", connection);
                //cmd.CommandText = "EXEC SchoolQuizReport @TopicID, @Date1, @Date2";
                cmd.Parameters.AddWithValue("@TopicID", quizParams.Topic.TopicID);
                cmd.Parameters.AddWithValue("@Date1", "2015/04/13");
                cmd.Parameters.AddWithValue("@Date2", "2015/04/16");
                cmd.CommandType = CommandType.StoredProcedure;

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);
                return ds.Tables[0];
                }

        }

        static private string GetConnectionString()
    {
        return "Data Source=(localdb)\\v11.0; Initial Catalog=UCAPDB-20140822124213; Integrated Security=True;";
    }

And my "View" (really aspx) code:

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="600">
    </rsweb:ReportViewer>
    </form>
</body>
</html>

My current error is:

The view at '~/Views/Reporting/GetSysWideQuizReport.aspx' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl.

UPDATE

I've tried the suggestion solution below and apparently fail pretty hard at it. So I kept going and I converted the RDL to an RDLC and used the design wizard to insert the call onto the ASPX page's ReportViewer. Now I'm getting a whole slew of weird AJAX errors.

Updated GetSysWideQuizReport.aspx:

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Quiz Report</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="915px" Height ="1000px" Font-Names="Lato" Font-Size="10pt" ShowBackButton="False" ShowRefreshButton="False" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt">
        <LocalReport ReportPath="ReportViews\System Quiz Report.rdlc">
            <DataSources>
                <rsweb:ReportDataSource DataSourceId="LocalDb" Name="DataSet1" />
            </DataSources>
        </LocalReport>
    </rsweb:ReportViewer>
        <asp:SqlDataSource ID="LocalDb" runat="server" ConnectionString="<%$ ConnectionStrings:LocalDb %>" SelectCommand="SystemQuizReport" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:FormParameter FormField="TopicID" Name="TopicID" Type="Int32" />
                <asp:FormParameter DbType="DateTime2" FormField="Date1" Name="Date1" />
                <asp:FormParameter DbType="DateTime2" FormField="Date2" Name="Date2" />
            </SelectParameters>
        </asp:SqlDataSource>
    </form>
</body>
</html>

The user form directly posts to this aspx page. Now for my errors:

Uncaught SyntaxError: Unexpected token <    ScriptResource.axd:1 
Uncaught SyntaxError: Unexpected token <    GetSysWideQuizReport.aspx:40
Uncaught Error: ASP.NET Ajax client-side framework failed to load.   ScriptResource.axd:1 
Uncaught SyntaxError: Unexpected token < Reserved.ReportViewerWebControl.axd:1 
Uncaught SyntaxError: Unexpected token < ScriptResource.axd:1 
Uncaught SyntaxError: Unexpected token <    GetSysWideQuizReport.aspx:49
Uncaught ReferenceError: Sys is not defined GetSysWideQuizReport.aspx:114 
Uncaught ReferenceError: Sys is not defined GetSysWideQuizReport.aspx:55 
Uncaught ReferenceError: $get is not defined
like image 465
Dreamcasting Avatar asked Jun 08 '15 12:06

Dreamcasting


People also ask

What is difference between MVC and mvc5?

ASP.NET Core can be used on Windows, Mac, or Linux, whereas ASP.NET MVC 5 can only be used for applications on Windows. The ASP.NET Core MVC is a framework for building web apps and APIs, optimized for use with ASP.NET Core.

Is ASP.NET MVC 5 outdated?

Is the framework outdated? ASP.NET MVC is no longer in active development. The last version update was in November 2018. Despite this, a lot of projects are using ASP.NET MVC for web solution development.


1 Answers

you have to use a ASPX page, just add a new folder (ex: WebForms) under the root of you MVC application and add a new ASPX webform in it.

in the aspx page you can add the reportviewer

<rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" Height="800" CssClass="reportViewer" ShowPrintButton="False"> </rsweb:ReportViewer>

in the code behind of the aspx page

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ReportFolder"]))
            {
                string reportpath = HttpUtility.HtmlDecode(Request.QueryString["ReportFolder"]);
                int aantalKeys = Request.Params.AllKeys.Length;

                List<ReportParameter> parameters = new List<ReportParameter>();
                for (int i = 1; i < aantalKeys; i++)
                {

                    string value = Request.Params[i];
                    string key = Request.Params.Keys[i];
                    if (key.Contains("_RAP"))
                    {
                        int index = key.IndexOf('_');
                        key = key.Substring(0, index);
                        ReportParameter parameter = new ReportParameter(key, HttpUtility.HtmlDecode(value));
                        parameters.Add(parameter);
                    }
                }
                this.RenderReport(reportpath, parameters);
            }

        }

    }

    private void RenderReport(string reportpath, List<ReportParameter> parameters = null)
    {
        string User = [ReportserverUser];
        string Pass = [ReportserverPass];
        string ReportServerUrl = [ResportserverUrl]];
        IReportServerCredentials irsc = new CustomReportCredentials(User, Pass, "");
        Uri uri = new Uri(ReportServerUrl);
        int lastSegment = uri.Segments.Length - 1;
        string page = uri.Segments[lastSegment];

        // EVENTS
        //reportViewer.Load += reportViewer_Load;
        //reportViewer.Unload += reportViewer_Unload;

        reportViewer.Visible = true;
        reportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
        reportViewer.ServerReport.ReportServerCredentials = irsc;
        reportViewer.ServerReport.ReportServerUrl = new Uri(uri.AbsoluteUri.Replace(page, ""));
        reportViewer.ServerReport.ReportPath = reportpath;
        if (parameters != null && parameters.Count != 0)
        {
            reportViewer.ServerReport.SetParameters(parameters);

        }
        reportViewer.ServerReport.Refresh();
    }

    private Dictionary<string, object> GetCurrentParameters()
    {

        var parameterCollection = reportViewer.ServerReport.GetParameters();


        var param = new Dictionary<string, object>();
        foreach (var p in parameterCollection)
        {
            var name = p.Name;
            if (p.DataType == ParameterDataType.DateTime)
            {
                var d = Convert.ToDateTime(p.Values[0]);
                param[name] = d.ToString("dd-MM-yyyy");
            }
            else
            {
                var values = p.Values.ToList();
                param[name] = values;
            }

        }


        return param;
    }

with this in place you should be able to navigate to http://localhost:port/webForms/yourpage.aspx?reportfolder=[reportpath]&param1_RAP=1&param2_RAP=ogjirewog

you need to provide the following param in the code behind - ReportserverUser & ReportserverPass: credentials that can login onto the reportserver interface and access the report. - Reportserver Url: this is the url to the reportserver Asxm webservice - reportpath: the path to the report in reportingserver (only the name, no extension at the end)

like image 120
Gelootn Avatar answered Oct 02 '22 18:10

Gelootn