Your action should return an ActionResult and if you have a stream, an easy way is to use the FilestreamResult
Notice there's a property to set the name of the file.
return new FileStreamResult(stream, "application/vnd.ms-excel")
{
FileDownloadName = "myfile.xslx"
};
Here's a sample to post the data from your form and download the generated file.
Create a model to hold the form values :
public class DownloadModel
{
public int InputA { get; set; }
public string InputB { get; set; }
}
Create a controller with two actions : one to display the form (Index) and an other to submit data and get the file (DownloadFile)
public class DownloadController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DownloadFile(DownloadModel model)
{
// read form value via model
System.Diagnostics.Debug.WriteLine(model.InputA);
System.Diagnostics.Debug.WriteLine(model.InputB);
// assume we create an an excel stream...
MemoryStream excelStream = new MemoryStream();
return new FileStreamResult(excelStream, "application/vnd.ms-excel")
{
FileDownloadName = "myfile.xslx"
};
}
}
Set the action form in the razor view Download/Index.cshtml to the DownloadFile action
@model WebApp.Models.DownloadModel
@{
ViewBag.Title = "DownloadFile";
}
<h2>DownloadFile</h2>
@using (Html.BeginForm("DownloadFile", "Download"))
{
@Html.TextBoxFor(model => model.InputA);
@Html.TextBoxFor(model => model.InputB);
<input type="submit" value="Save" name="submitButton" />
}