使用以下代码:
static string RenderViewToString(ControllerContext context,string viewPath,object model = null,bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
此行之后:
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
执行时,我发现viewEngineResult为NULL,我认为这意味着即使我将视图正确地放置在同一路径中,也找不到它。
我不确定为什么您的代码返回null,但这在控制器的上下文中对我有效:
public string RenderRazorViewToString(string viewName, object model = null)
{
ViewData.Model = model;
using (var sw = new System.IO.StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
用法:
var result = RenderRazorViewToString("_GridHeaderStudentCell");
不过,您可以很容易地将其修改为将ControllerContext作为参数。
可能找不到您的视图,请确保您的视图位于同名文件夹中,像这样的东西查找"日志"视图:
- Views文件夹
- 日志文件夹
- logs.cshtml文件
- 日志文件夹