?
Solved

MVC - download file using memory contents (model?)

Posted on 2012-03-21
6
Medium Priority
?
443 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:Tom Knowlton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 14

Accepted Solution

by:
binaryevo earned 2000 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:Tom 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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:Tom 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:Tom Knowlton
ID: 37757611
Thanks!
0

Featured Post

Command Line Tips and Tricks

The command line is a powerful tool at the disposal of every Linux user. Although Linux distros come with beautiful user interfaces, it's worthwhile to learn the command line because it allows you to do a number of things that you otherwise cannot do from the GUI.  

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

752 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