Vince Ashby-Smith
Vince Ashby-Smith

Reputation: 1192

MVC C# Download file and save as dialog

Hi all wondering if someone can help; i've written this code which will generate an excel spreadsheet and save it to a specified location. I want to then display a "Save as" dialogue box by reading the file from the stored location and then asking then user where they want to store it. The excel file is being generated fine and i can open it normally! However my problem is the code i've written seems to be outputting the file directly to my browser, so i get all the contents of the excel file on my browser screen, not displaying the save as dialogue box as expected!

public ActionResult FormSuccess()
        {
            String FileName = System.Configuration.ConfigurationManager.AppSettings["FileName"].ToString();
            String FilePath = System.Configuration.ConfigurationManager.AppSettings["FileSaveLocation"].ToString();
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "application/vnd.xls";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + FileName);
            response.End();

            return PartialView("FormSuccess");
        }

Upvotes: 3

Views: 29855

Answers (2)

James McCormack
James McCormack

Reputation: 9934

Yo Vince, how's tricks? Still wearing the medallion? :)

Shouldn't you be using FileContentResult instead of PartialView? You won't be able to return the file AND the HTML "success" content in the same call - you should probably call the PartialView first, which would then use javascript to open the FileContentResult URL in a new window.

See this: http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files

and this url as well :

http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx

Upvotes: 6

Eduard
Eduard

Reputation: 3216

I think that your problem is that you return PartialView. Let me give you small exmaple of my implemetation:

    public ActionResult FileXls()
    {
        var output = new MemoryStream();
        var writer = new StreamWriter(output);

        //create your workbook excel file
        ....
        //workbook.Save(output);

        writer.Flush();
        output.Position = 0;
        return File(output, "text/excel", "file.xls");
    }

Upvotes: 5

Related Questions