Asp.net MVC ViewEngineResult +嵌入视图

时间:2013-10-03 08:02:16

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

我有一个工作函数,它返回一个已处理的视图(或部分视图)

我将此函数称为向视图发送虚拟路径,例如:

string viewHtml = GetViewPageHtml(this, model, "~/Views/PartialView.cshtml");

public static string GetViewPageHtml(Controller controller, object model, string viewName)
{
    ViewEngineResult result = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);

    if (result.View == null)
        throw new Exception(string.Format("View Page {0} was not found", viewName));

    controller.ViewData.Model = model;
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (System.Web.UI.HtmlTextWriter output = new System.Web.UI.HtmlTextWriter(sw))
        {
            ViewContext viewContext = new ViewContext(controller.ControllerContext, result.View, controller.ViewData, controller.TempData, output);
            result.View.Render(viewContext, output);
        }
    }

    return sb.ToString();
}

是否有任何解决方案可以使此功能找到嵌入式视图?

如果我有一个嵌入式视图并调用相同的函数,则它找不到页面:

// not working
string viewHtml = GetViewPageHtml(this, model, "Application1.Views.EmbededPartialView.cshtml");

1 个答案:

答案 0 :(得分:0)

有两种方法可以实现这样的解决方案:

  1. 而不是资源中的视图,考虑RazorGenerator,它将视图编译成代码,并具有ViewEngine
  2. 第二种方式是使用VirtualPAthProvider - 有关此内容的更多信息,请访问:Using VirtualPathProvider to load ASP.NET MVC views from DLLs