Note that there are some explanatory texts on larger screens.

plurals
  1. POActionMethod to return excel application content
    primarykey
    data
    text
    <p>What's the correct method to return application/ms-excel content type from an action method in MVC? </p> <p>I've tried creating a controller action method and passing the controller context, such as;</p> <pre><code>public void ExportToExcel(MyViewModel model, ControllerContext context) { .... build up html or xml excel output in Writer context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "applicaton/vnd.ms-excel"; context.HttpContext.Response.AddHeader(.. etc.); context.HttpContext.Response.Write(Writer.ToString()); context.HttpContext.Response.End(); } </code></pre> <p>When trying to use the controller context as above I get a method or operation not implemented exception when calling any method of the Response object.</p> <p>I've also tried returning a FileResult, FileContentResult and ContentResult action result types which seem to just throw my content to the browser.</p> <p>EDIT: Here's my code for the ExcelResult class;</p> <pre><code>public class ExcelResult : ActionResult { private string _content = String.Empty; public string Content { get { return _content; } set { _content = value; } } public ExcelResult(string content) { this.Content = content; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "application/vnd.ms-excel"; context.HttpContext.Response.Charset = "iso-8859-1"; context.HttpContext.Response.BufferOutput = true; context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename = exportdata.xls"); context.HttpContext.Response.Write(this.Content); context.HttpContext.Response.End(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload