Solved

MVC - download file using memory contents (model?)

Posted on 2012-03-21
6
393 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
Comment Utility
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
Comment Utility
Is there a way to prompt for a file name from the user?
0
 
LVL 14

Expert Comment

by:binaryevo
Comment Utility
What do you mean prompt for a filename?  Are you referring to open / save as dialog by the browser?
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 14

Expert Comment

by:binaryevo
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

763 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

7 Experts available now in Live!

Get 1:1 Help Now