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

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

我有下一个代码:

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

还有下一个问题—— 我该怎么做才能使我的Action 返回生成的 HTML 作为文件供下载。 提前致谢!

最佳答案

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 放入单独的类中。

关于c# - ASP.NET MVC 将 ViewResult 作为 html 文件返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009509/

相关文章:

c# - 通过 WCF 服务传递枚举

c# - 在c#中获取字符串之间的字符串

c# - MVC 应用程序中的文件下载

c# - 为什么编译器至少不警告 this == null

asp.net-mvc - 底层 View 设置后如何访问 ViewBag.Title?

c# - 转直播时401未授权

c# - ASP.NET MVC 4 表单发布变量在接收 Controller 中为空

c# - 如何根据传递给 ASP.NET MVC 中的 Controller /操作的属性值有条件地绑定(bind)到 ninject?

asp.net-mvc - MVC 4 列表模型向 Controller 返回 null

c# - 使用 react 性扩展每秒按顺序获取下一个事件