Skip to content

Instantly share code, notes, and snippets.

@VictorUUsoro
Forked from bjcull/WordDocumentAttribute.cs
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VictorUUsoro/9120273c572e27c8a1e7 to your computer and use it in GitHub Desktop.
Save VictorUUsoro/9120273c572e27c8a1e7 to your computer and use it in GitHub Desktop.
A Filter Attribute that lets you download an ASP.NET MVC View as a Word Document
public class WordDocumentAttribute : ActionFilterAttribute
{
public string DefaultFilename { get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResult;
if (result != null)
result.MasterName = "~/Views/Shared/_LayoutWord.cshtml";
filterContext.Controller.ViewBag.WordDocumentMode = true;
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var filename = filterContext.Controller.ViewBag.WordDocumentFilename;
filename = filename ?? DefaultFilename ?? "Document";
filterContext.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("filename={0}.doc", filename));
filterContext.HttpContext.Response.ContentType = "application/msword";
base.OnResultExecuted(filterContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment