Solved

MVC - download file using memory contents (model?)

Posted on 2012-03-21
6
405 Views
Last Modified: 2012-03-23
Brand new to MVC.

I have a web page that generates a report.

If the report has 1 or more rows of data, I want to show a "Download Report" button which will take that data and allow for it to be downloaded into some sort of .CSV file.

Possible?

Recommendations?  Tutorials?  Websites?


Thanks!

Tom
0
Comment
Question by:knowlton
  • 3
  • 3
6 Comments
 
LVL 14

Accepted Solution

by:
binaryevo earned 500 total points
ID: 37752686
in your action, you can have Return File.


Something like this:

MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.ms-excel", "TestExcelFile.xlsx");

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 37753082
Is there a way to prompt for a file name from the user?
0
 
LVL 14

Expert Comment

by:binaryevo
ID: 37753117
What do you mean prompt for a filename?  Are you referring to open / save as dialog by the browser?
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 14

Expert Comment

by:binaryevo
ID: 37753129
If you mean to allow the user to input the name they want to save the file as then yes you can just popup a modal dialog via javascript and pass in the filename into the action on post.  Once you have the filename in the action, just replace the TestExcelFile.xlsx in the return File code with the name passed in.
0
 
LVL 5

Author Comment

by:knowlton
ID: 37753482
I am new to MVC, in fact, this is my first project.  Somebody else wrote the page, I am just attempting to modify it.

I need help getting the javascript setup and obtaining the file name from the dialog.


I will provide my current source code for "model","view" and "controller".  Hopefully between those 3 files you can help me get this in place.

model
using System;
using System.Collections.Generic;
using System.Linq;
using BarclayPortal.DAL.Models;

namespace BarclayPortal.Website.Models
{

    public class BarclayReportModel
    {

        public DateTime date_received { get; set; }

        public DateTime date_export { get; set; }

        public int? do_not_solicit { get; set; }

        public int? undeliverable { get; set; }

        public int? exceptions_with_letters { get; set; }

        public int? exceptions_without_letters { get; set; }

        public int? correspondence { get; set; }

        // 2012-03-21 BD: Notified by PR that client has requested this to be removed
        // public int? estimated_mail_received { get; set; }

        public int? actual_mail_received { get; set; }

        public int? pobox_mail_received { get; set; }

        public int? non_pobox_mail_received { get; set; }

        public int? white_mail { get; set; }

        public int? letters_mailed { get; set; }

        public int? blue_green_apps { get; set; }

        public int Julian { get; set; }

        public int Partial { get; set; }

        public int Direct { get; set; }

        public int Full { get; set; }

        public Dictionary<int, int> CampaignCounts { get; set; }

        public BarclayReportModel()
        {
            CampaignCounts = new Dictionary<int, int>();
        }

        public static BarclayReportModel ConvertFrom(spBarclayReportRecord item)
        {
            BarclayReportModel retVal = new BarclayReportModel
            {
                date_received = item.date_received,
                date_export = item.date_export,
                do_not_solicit = item.do_not_solicit,
                undeliverable = item.undeliverable,
                exceptions_with_letters = item.exceptions_with_letters,
                exceptions_without_letters = item.exceptions_without_letters,
                correspondence = item.correspondence,
                // estimated_mail_received = item.estimated_mail_received,
                actual_mail_received = item.actual_mail_received,
                pobox_mail_received = item.pobox_mail_received,
                non_pobox_mail_received = item.non_pobox_mail_received,
                white_mail = item.white_mail,
                letters_mailed = item.letters_mailed,
                blue_green_apps = item.blue_green_apps,
                Julian = item.Julian, 
                Partial = item.Partial, 
                Direct = item.Direct, 
                Full = item.Full, 
                CampaignCounts = item.CampaignCounts
            };
            return retVal;
        }

        public static List<BarclayReportModel> ConvertFrom(List<spBarclayReportRecord> items)
        {
            return items.Select(item => ConvertFrom(item)).ToList();
        }
    }

}

Open in new window



view
@model BarclayReportAndParameters
@using BarclayPortal.Website.Models

@{
    ViewBag.Title = "Report";
    string errorMessage = "";
    if (ViewBag.ErrorMessage != null)
    {
        errorMessage = ViewBag.ErrorMessage.ToString();
    }
    Dictionary<int, string> selectOptions = new Dictionary<int, string>();
    foreach (BarclayReportAndParameters.PricePointOptions option in Enum.GetValues(typeof(BarclayReportAndParameters.PricePointOptions)))
    {
        selectOptions.Add((int) option, option.ToString());
    }
}

@{ Html.RenderPartial("SubmenuNav"); }

@if (!string.IsNullOrWhiteSpace(errorMessage))
{
    <p class="MT10 MB10 ML10 MR10 error">@errorMessage</p>
}

@using (Html.BeginForm("Report", "Reports", FormMethod.Post, new { id = "frmReportParameters" }))
{
    <div>
        <fieldset>
            <legend>Parameters</legend>
            <div class="FL MR15">
                <div class="editor-label"><label for="BeginDate">Begin Date</label></div>
                <div class="editor-field">
                    <input type="text" id="BeginDate" name="BeginDate" value="@Model.BeginDate.ToString("MM/dd/yyyy")" maxlength="10" />
                </div>
            </div>
            <div class="FL MR15">
                <div class="editor-label"><label for="EndDate">End Date</label></div>
                <div class="editor-field">
                    <input type="text" id="EndDate" name="EndDate" value="@Model.EndDate.ToString("MM/dd/yyyy")" maxlength="10" />
                </div>
            </div>
            <div class="FL MR15">
                <div class="editor-label"><label for="PricePoint">Price Points</label></div>
                <div class="editor-field">
                    <select id="PricePoint" name="PricePoint">
                        @foreach(KeyValuePair<int, string> kvp in selectOptions)
                        {
                            if ((int) Model.PricePoint == kvp.Key)
                            {
                                <option value="@kvp.Key" selected="selected">@kvp.Value</option>
                            }
                            else
                            {
                                <option value="@kvp.Key">@kvp.Value</option>
                            }
                        }
                    </select>
                </div>
            </div>
            <div class="FL MR15">
                <!-- <div class="editor-label"><label> <br /></label></div> -->
                <div class="editor-field">
                    <input class="MT25" type="submit" value="Generate Report" />
                </div>                
            </div>
            <div class="clear"></div>
        </fieldset>
    </div>
}



@using (Html.BeginForm("ReportTomNew", "Reports", FormMethod.Post, new { id = "frmReportParameters" }))
{
    <div>
        <fieldset>            
            <div class="FL MR15">
                <!-- <div class="editor-label"><label> <br /></label></div> -->
                <div class="editor-field">
                    <input class="MT25" type="submit" value="Download Report" />
                </div>                
            </div>
            <div class="clear"></div>
        </fieldset>
    </div>
}


@if (Model.ReportRecords != null)
{
    <div style="overflow: auto; padding-top: 20px; padding-bottom: 20px; min-height: 420px;">
        <table id="tblReportRecords">
            <thead>
                <tr>
                    <th>Date Received</th>
                    <th>Julian</th>
                    <th>Date Export</th>
                    <th>Partial</th>
                    <th>Direct</th>
                    <th>Full</th>
                    <th>Do Not Solicit</th>
                    <th>Undeliverable</th>
                    <th>Exceptions With Letters</th>
                    <th>Exceptions Without Letters</th>
                    <th>Correspondence</th>
                    <th>Actual Mail Received</th>
                    <th>PO Box mail Received</th>
                    <th>Non PO Box Mail Received</th>
                    <th>White Mail</th>
                    <th>Letters Mailed</th>
                    <th>Blue Green Apps</th>
                    <th>Campaign Counts</th>
                </tr>
            </thead>
            <tbody>
                @foreach (BarclayReportModel item in Model.ReportRecords)
                {
                    <tr>
                        <td>@item.date_received.ToString("MM/dd/yyyy")</td>
                        <td>@item.Julian</td>
                        <td>@item.date_export.ToString("MM/dd/yyyy")</td>
                        <td>@item.Partial</td>
                        <td>@item.Direct</td>
                        <td>@item.Full</td>
                        <td>@item.do_not_solicit</td>
                        <td>@item.undeliverable</td>
                        <td>@item.exceptions_with_letters</td>
                        <td>@item.exceptions_without_letters</td>
                        <td>@item.correspondence</td>
                        <td>@item.actual_mail_received</td>
                        <td>@item.pobox_mail_received</td>
                        <td>@item.non_pobox_mail_received</td>
                        <td>@item.white_mail</td>
                        <td>@item.letters_mailed</td>
                        <td>@item.blue_green_apps</td>
                        <td>@item.CampaignCounts.Count</td>
                    </tr>                
                }
            </tbody>
    </table>
    </div>
}

<link href="@Url.Content("~/Content/dataTables/jquery.dataTables.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/dataTables/jquery.dataTables.min.js")" type="text/javascript"></script>

<script type="text/javascript" language="javascript">

    $(document).ready(function () {
        $('#BeginDate').datepicker();
        $('#EndDate').datepicker();
        var l = $('#tblReportRecords').length;
        if (l > 0)
        {
            $('#tblReportRecords').dataTable();
        }
    });

</script>

Open in new window



controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BarclayPortal.Website.Helpers;
using BarclayPortal.Website.Models;
using System.Data;
using System.IO;
using System.Text;

namespace BarclayPortal.Website.Controllers
{
    public class ReportsController : Controller
    {
        //
        // GET: /Reports/

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Report(DateTime? loadBeginDate, DateTime? loadEndDate)
        {
            BarclayReportAndParameters model = new BarclayReportAndParameters
            {
                BeginDate = DateTime.Now.AddDays(-1),
                EndDate = DateTime.Now,
                PricePoint = BarclayReportAndParameters.PricePointOptions.NONE, 
                ReportRecords = null
            };
            if (loadBeginDate != null && loadEndDate != null && loadBeginDate.Value <= loadEndDate.Value)
            {
                model.BeginDate = loadBeginDate.Value;
                model.EndDate = loadEndDate.Value;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Report(BarclayReportAndParameters model)
        {
            try
            {
                model.ReportRecords = DALHelper.GetReport(model.parameterBeginDate, model.parameterEndDate, model.parameterPricePoint);
                SessionHelper.LastGeneratedBarclayReportAndParameters = model;
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                model.ReportRecords = null;
            }

            

            return View(model);
        }




        [HttpGet]
        public ActionResult ReportTomNew(DateTime? loadBeginDate, DateTime? loadEndDate)
        {
            BarclayReportAndParameters model = new BarclayReportAndParameters
            {
                BeginDate = DateTime.Now.AddDays(-1),
                EndDate = DateTime.Now,
                PricePoint = BarclayReportAndParameters.PricePointOptions.NONE,
                ReportRecords = null
            };
            if (loadBeginDate != null && loadEndDate != null && loadBeginDate.Value <= loadEndDate.Value)
            {
                model.BeginDate = loadBeginDate.Value;
                model.EndDate = loadEndDate.Value;
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult ReportTomNew(BarclayReportAndParameters model)
        {
            try
            {
                model = SessionHelper.LastGeneratedBarclayReportAndParameters;
                CSVUtility.GetCSVNew();              
                
                //var filename = "";
                //var contenttype = "text/csv";
                //Response.Clear();
                //Response.ContentType = contenttype;
                //Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                //Response.BinaryWrite(Encoding.ASCII.GetBytes(CSVUtility.stream));
                //Response.End();

                //MemoryStream stream = new MemoryStream();
                //workbook.SaveAs(stream);
                return File(Encoding.ASCII.GetBytes(CSVUtility.stream), "application/vnd.ms-excel", "TestExcelFile.csv");

            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                model.ReportRecords = null;
            }

            return View(model);
        }

        




    }

}

Open in new window

0
 
LVL 5

Author Closing Comment

by:knowlton
ID: 37757611
Thanks!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now