是否在使用ViewRenderer

时间:2016-07-25 23:40:06

标签: c# asp.net-mvc-5 viewrendering

我正在使用ViewRenderer将查看结果写入如下文件:

    public class WriteViewToFile
    {
        private DetailsController controller = ViewRenderer.CreateController<DetailsController>();

        public void WriteDataToFile(ContextDB db, DataViewModel model, string fileName)
        {

            string html = ViewRenderer.RenderView("~/Views/Details/TemplateForData.cshtml", model, controller.ControllerContext);

            File.WriteAllText(fileName, html);
            // controller.dispose();
        }
        public void WriteOtherToFile(ContextDB db, OtherViewModel model, string fileName)
        {

            string html = ViewRenderer.RenderView("~/Views/Details/TemplateForOther.cshtml", model, controller.ControllerContext);

            File.WriteAllText(fileName, html);
            // controller.dispose();
        }
    }

我应该在最后添加controller.dispose()还是自动完成?如果是的话,有没有办法在调用任何方法后处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

您可以将该行为分为自己的方法:

public void WriteToFile(ContextDB db, DataViewModel model, string fileName)
{
    string html = RenderView(model);
    File.WriteAllText(fileName, html);
}

private string RenderView(model)
{
    using(var controller = ViewRenderer.CreateController<DetailsController>())
    {
        return ViewRenderer.RenderView("~/Views/Details/Template.cshtml", 
            model, controller.ControllerContext);
    }
}

现在正在创建,使用和处理您的控制器。