ASP.NET MVC将ViewResult作为html文件返回

时间:2013-11-15 19:55:46

标签: c# asp.net-mvc asp.net-mvc-4

我有下一个代码:

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

还有下一个问题 - 如何使我的操作将生成的HTML作为文件返回下载。 谢谢你!

1 个答案:

答案 0 :(得分:17)

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;
                }
          }

注意:这只是一个例子。我建议将 GetViewToString 放入一个单独的类中。