Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

MVC - download file using memory contents (model?)

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
ASKER CERTIFIED SOLUTION
Avatar of binaryevo
binaryevo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tom Knowlton

ASKER

Is there a way to prompt for a file name from the user?
What do you mean prompt for a filename?  Are you referring to open / save as dialog by the browser?
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.
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

Thanks!