10

i have next code:

  public class TemplateController : Controller
    {
        public ActionResult GetThreeColomnTemplate(SettingViewModel model)
        {
         ...
         return View("ThreeColomn",model);
        }
    }

And have next question - How can I do to make my Action to returns generated HTML as file for download. Thanks advance!

1 Answer 1

19
public class TemplateController : Controller
   {
       public ActionResult GetThreeColomnTemplate(SettingViewModel model)
        {
          ...
          return View("ThreeColomn",model);
        }


       public ActionResult GetThreeColomnTemplateAsFile(SettingViewModel model)
         {
            SettingViewModel model = ...

            ViewEngineResult result = ViewEngines.Engines.FindView(this.ControllerContext, "ThreeColomn", "_Layout");
                   string htmlTextView = GetViewToString(this.ControllerContext, result, model);

                    byte[] toBytes = Encoding.Unicode.GetBytes(htmlTextView);

                    return File(toBytes, "application/file","template.html");
             }


            private string GetViewToString(ControllerContext context, ViewEngineResult result, object model)
                {
                    string viewResult = "";
                    var viewData = ViewData; 
                    viewData.Model = model;           
                    TempDataDictionary tempData = new TempDataDictionary();
                    StringBuilder sb = new StringBuilder();
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        {
                            ViewContext viewContext = new ViewContext(context,
                                result.View, viewData, tempData, output);
                            result.View.Render(viewContext, output);
                        }
                        viewResult = sb.ToString();
                    }
                    return viewResult;
                }
          }

Note: This only example. I advise to put GetViewToString into in a separate class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.