Skip to content

Instantly share code, notes, and snippets.

@ycaroafonso
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save ycaroafonso/e517d4ea21fcc79e1bc0 to your computer and use it in GitHub Desktop.

Select an option

Save ycaroafonso/e517d4ea21fcc79e1bc0 to your computer and use it in GitHub Desktop.
Download do HTML de uma view
public ActionResult Download(int id)
{
var objetoEntity = ...;
ViewEngineResult result = ViewEngines.Engines.FindView(this.ControllerContext, "Visualizar", "_Layout");
string htmlTextView = GetViewToString(this.ControllerContext, result, objetoEntity);
byte[] toBytes = System.Text.Encoding.Unicode.GetBytes(htmlTextView);
return File(toBytes, "application/file", "template.doc");
}
private string GetViewToString(ControllerContext context, ViewEngineResult result, object model)
{
string viewResult = "";
var viewData = ViewData;
viewData.Model = model;
TempDataDictionary tempData = new TempDataDictionary();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (System.Web.UI.HtmlTextWriter output = new System.Web.UI.HtmlTextWriter(sw))
{
ViewContext viewContext = new ViewContext(context,
result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
}
viewResult = sb.ToString();
}
return viewResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment