在 web mvc2 中将报表绑定到reportviewer

发布于 2024-10-21 23:13:49 字数 1460 浏览 1 评论 0原文

我有 asp.net MVC2 应用程序。 我正在使用 VS2008,想要将生成的报告从我的控制器连接到报告查看器。

有什么想法吗?

到目前为止我有这个代码 “控制器”

//should pass data to report
 public ActionResult GenerateReport()
      {


        LocalReport report = new LocalReport();
        report.ReportPath = Server.MapPath("~/Reports/KingsCourt.rdlc");

        List<InvoiceRow> rows = new List<InvoiceRow>();

        rows.Add(new InvoiceRow { name = "Testing item", value = (decimal)25.85 });
        rows.Add(new InvoiceRow { name = "Testing item2", value = (decimal)5.15 });
        ReportDataSource source = new ReportDataSource("InvoiceRow", rows);
        report.DataSources.Add(source);

        ViewData["InvoiceRow"] = report;
        return View();
      }

和视图页面:

 <form id="form1" runat="server">

  <h2>GenerateReport</h2>
  <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" 
      Font-Size="8pt" Height="400px" Width="400px">
    <LocalReport ReportPath="Reports\KingsCourt.rdlc">
      <DataSources>
        <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="InvoiceRow" />
      </DataSources>
    </LocalReport>


  </rsweb:ReportViewer>    

  <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Rows" 
      TypeName="Accounts.Classes.Invoices"></asp:ObjectDataSource>
 </form>

I have asp.net MVC2 application.
I am using VS2008 and want to hook up generated report from my controller to reportviewer.

any ideas?

so far i have this code
"Controller"

//should pass data to report
 public ActionResult GenerateReport()
      {


        LocalReport report = new LocalReport();
        report.ReportPath = Server.MapPath("~/Reports/KingsCourt.rdlc");

        List<InvoiceRow> rows = new List<InvoiceRow>();

        rows.Add(new InvoiceRow { name = "Testing item", value = (decimal)25.85 });
        rows.Add(new InvoiceRow { name = "Testing item2", value = (decimal)5.15 });
        ReportDataSource source = new ReportDataSource("InvoiceRow", rows);
        report.DataSources.Add(source);

        ViewData["InvoiceRow"] = report;
        return View();
      }

and View page:

 <form id="form1" runat="server">

  <h2>GenerateReport</h2>
  <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" 
      Font-Size="8pt" Height="400px" Width="400px">
    <LocalReport ReportPath="Reports\KingsCourt.rdlc">
      <DataSources>
        <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="InvoiceRow" />
      </DataSources>
    </LocalReport>


  </rsweb:ReportViewer>    

  <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Rows" 
      TypeName="Accounts.Classes.Invoices"></asp:ObjectDataSource>
 </form>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪眸﹌ 2024-10-28 23:13:49

您始终可以将 ASP.NET WebForms 与 MVC 结合使用。我想这是唯一的方法。
我在此处为您准备了一个示例。

您可以创建一个文件夹来放置您的 asp.net WebForm 和报告 (rdlc)。
我已将架构 (xsd) 和数据 (xml) 放入同一文件夹中,但显然,我猜您将使用数据库。
我已将路线映射到报告,如下所示:

    //Custom route for reports
    routes.MapRoute(
     "ReportRoute",
     "Reports/{reportname}",                
     "~/Reports/{reportname}.aspx"
     );

更新:

我准备了一些ASP.NET MVC3 (MvcReportViewerMVC3) 的代码
这与 Web 表单上的一些细微更改几乎相同:我集成了新的 ReportViewer (10),并且必须将 ScriptManager 添加到同一页面:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

我也更改了 WebForm 代码,因为看起来 page_load事件被调用了很多次:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
    ....
    }
}

希望有帮助。

You can always use ASP.NET WebForms with MVC. I guess this is the only way to do it.
I've prepared a sample for you here.

You can create a folder where you're going to put your asp.net WebForm and the report (rdlc).
I've put in the same folder the schema (xsd) and the data (xml) but, obviously, I guess you're going to use the database.
I've mapped the route to the report(s) like this:

    //Custom route for reports
    routes.MapRoute(
     "ReportRoute",
     "Reports/{reportname}",                
     "~/Reports/{reportname}.aspx"
     );

UPDATE:

I have prepared some code for ASP.NET MVC3 (MvcReportViewerMVC3).
It is pretty much the same with some minor changes on the webform: I've integrated the new ReportViewer (10) and I had to add the ScriptManager to the same page:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

I've changed the WebForm code as well cause it appears that page_load event is called loads of times:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
    ....
    }
}

Hope it helps.

溇涏 2024-10-28 23:13:49

我怀疑在asp.net mvc中使用reportviewer是可能的。
您可以做的最好的事情就是返回报告 渲染为图像

I doubt usage of reportviewer in asp.net mvc is possible.
Best thing You can do is return report rendered as an image.

聽兲甴掵 2024-10-28 23:13:49

帕维尔,我为此挣扎了一段时间。最后决定实现我自己的 ActionResult 并流式传输 PDF 文件。
这是我的操作:

public ActionResults.DownloadFileResult PrintReport()
{
    rvDocument = new WebForms.ReportViewer();

    rvDocument.ProcessingMode = ProcessingMode.Local;

    LocalReport report = rvDocument.LocalReport;
    report.ReportPath = Server.MapPath("~/Reports/KingsCourt.rdlc");

    string sGuid = Guid.NewGuid.ToString.Replace("-", "");

    List<InvoiceRow> rows = new List<InvoiceRow>();

    rows.Add(new InvoiceRow { name = "Testing item", value = (decimal)25.85 });
    rows.Add(new InvoiceRow { name = "Testing item2", value = (decimal)5.15 });
    ReportDataSource source = new ReportDataSource("InvoiceRow", rows);
    report.DataSources.Add(source);

    rvDocument.LocalReport.Refresh();

    string sFileName = Path.Combine("<temp folder>", sGuid + ".PDF");
    byte[] StreamBytes = null;

    string mimeType = "";
    string encoding = "";
    string filenameExtension = "";
    string[] streamids = null;
    Warning[] warnings = null;

    StreamBytes = rvDocument.LocalReport.Render("PDF", null, mimeType, encoding, filenameExtension, streamids, warnings);
    if ((StreamBytes != null)) {
        try {
            using (FileStream fs = new FileStream(sFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Write)) {
                fs.Write(StreamBytes, 0, StreamBytes.Length);
            }
        } catch (Exception ex) {
            // Log.Logger.WriteException(string.Empty, ex, Log.Logger.LogTypes.Error, this.GetType, "Report001_Load");
        }
        StreamBytes = null;
    }

    BPMVC.ActionResults.DownloadFileResult oPdfToStream = new BPMVC.ActionResults.DownloadFileResult();
    {
        oPdfToStream.FileName = sFileName;
        oPdfToStream.ContentType = "application/pdf";
        oPdfToStream.DocumentName = "ReportName.pdf";
    }

    return (oPdfToStream);

}

这是我的自定义 ActionResult

using System.Web.Mvc;
using System.Web;
using System.IO;

namespace ActionResults
{

    public class DownloadFileResult : ActionResult
    {

        #region " Public Properties "

        private string _VirtualPath = "";
        public string VirtualPath {
            get { return (_VirtualPath); }
            set { _VirtualPath = value; }
        }

        private string _FileName = "";
        public string FileName {
            get { return (_FileName); }
            set { _FileName = value; }
        }

        private string _ContentType = "text/html";
        public string ContentType {
            get { return (_ContentType); }
            set { _ContentType = value; }
        }

        private string _DocumentName = "";
        public string DocumentName {
            get { return (_DocumentName); }
            set { _DocumentName = value; }
        }

        #endregion


        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            if ((context == null)) {
                throw new ArgumentNullException("context");
            }

            if (string.IsNullOrEmpty(this.FileName) && string.IsNullOrEmpty(this.VirtualPath)) {
                throw new ArgumentNullException("FileName is Empty");
            }


            string filePath = "";

            if (string.IsNullOrEmpty(this.VirtualPath)) {
                filePath = this.FileName;
            } else {
                filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
            }

            if (string.IsNullOrEmpty(this.DocumentName)) {
                this.DocumentName = Path.GetFileName(filePath);
            }

            {
                context.HttpContext.Response.Clear();
                context.HttpContext.Response.ClearHeaders();
                context.HttpContext.Response.ClearContent();
                context.HttpContext.Response.ContentType = this.ContentType;
                context.HttpContext.Response.AddHeader("Content-Type", this.ContentType);
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.DocumentName + "\"");
                context.HttpContext.Response.TransmitFile(this.FileName);
                context.HttpContext.Response.End();
            }

        }

    }

}

Pavel, I've struggled a little while with that. At the end decided to implement my own ActionResult and streaming a PDF file.
This is my action:

public ActionResults.DownloadFileResult PrintReport()
{
    rvDocument = new WebForms.ReportViewer();

    rvDocument.ProcessingMode = ProcessingMode.Local;

    LocalReport report = rvDocument.LocalReport;
    report.ReportPath = Server.MapPath("~/Reports/KingsCourt.rdlc");

    string sGuid = Guid.NewGuid.ToString.Replace("-", "");

    List<InvoiceRow> rows = new List<InvoiceRow>();

    rows.Add(new InvoiceRow { name = "Testing item", value = (decimal)25.85 });
    rows.Add(new InvoiceRow { name = "Testing item2", value = (decimal)5.15 });
    ReportDataSource source = new ReportDataSource("InvoiceRow", rows);
    report.DataSources.Add(source);

    rvDocument.LocalReport.Refresh();

    string sFileName = Path.Combine("<temp folder>", sGuid + ".PDF");
    byte[] StreamBytes = null;

    string mimeType = "";
    string encoding = "";
    string filenameExtension = "";
    string[] streamids = null;
    Warning[] warnings = null;

    StreamBytes = rvDocument.LocalReport.Render("PDF", null, mimeType, encoding, filenameExtension, streamids, warnings);
    if ((StreamBytes != null)) {
        try {
            using (FileStream fs = new FileStream(sFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Write)) {
                fs.Write(StreamBytes, 0, StreamBytes.Length);
            }
        } catch (Exception ex) {
            // Log.Logger.WriteException(string.Empty, ex, Log.Logger.LogTypes.Error, this.GetType, "Report001_Load");
        }
        StreamBytes = null;
    }

    BPMVC.ActionResults.DownloadFileResult oPdfToStream = new BPMVC.ActionResults.DownloadFileResult();
    {
        oPdfToStream.FileName = sFileName;
        oPdfToStream.ContentType = "application/pdf";
        oPdfToStream.DocumentName = "ReportName.pdf";
    }

    return (oPdfToStream);

}

and this is my custom ActionResult

using System.Web.Mvc;
using System.Web;
using System.IO;

namespace ActionResults
{

    public class DownloadFileResult : ActionResult
    {

        #region " Public Properties "

        private string _VirtualPath = "";
        public string VirtualPath {
            get { return (_VirtualPath); }
            set { _VirtualPath = value; }
        }

        private string _FileName = "";
        public string FileName {
            get { return (_FileName); }
            set { _FileName = value; }
        }

        private string _ContentType = "text/html";
        public string ContentType {
            get { return (_ContentType); }
            set { _ContentType = value; }
        }

        private string _DocumentName = "";
        public string DocumentName {
            get { return (_DocumentName); }
            set { _DocumentName = value; }
        }

        #endregion


        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            if ((context == null)) {
                throw new ArgumentNullException("context");
            }

            if (string.IsNullOrEmpty(this.FileName) && string.IsNullOrEmpty(this.VirtualPath)) {
                throw new ArgumentNullException("FileName is Empty");
            }


            string filePath = "";

            if (string.IsNullOrEmpty(this.VirtualPath)) {
                filePath = this.FileName;
            } else {
                filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
            }

            if (string.IsNullOrEmpty(this.DocumentName)) {
                this.DocumentName = Path.GetFileName(filePath);
            }

            {
                context.HttpContext.Response.Clear();
                context.HttpContext.Response.ClearHeaders();
                context.HttpContext.Response.ClearContent();
                context.HttpContext.Response.ContentType = this.ContentType;
                context.HttpContext.Response.AddHeader("Content-Type", this.ContentType);
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.DocumentName + "\"");
                context.HttpContext.Response.TransmitFile(this.FileName);
                context.HttpContext.Response.End();
            }

        }

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文