ActionMethod to return excel application content
What's the correct method to return application/ms-excel content type from an action method in MVC?
I've tried creating a controller action method and pass开发者_如何学编程ing the controller context, such as;
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();
}
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.
I've also tried returning a FileResult, FileContentResult and ContentResult action result types which seem to just throw my content to the browser.
EDIT: Here's my code for the ExcelResult class;
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();
}
}
FYI. My problem was due to the fact I was trying to change content-type from an AJAX callback. Always ensure you are submitting a form before changing the content-type.
精彩评论