gpt4 book ai didi

c# - 找不到 View

转载 作者:行者123 更新时间:2023-11-30 13:00:01 25 4
gpt4 key购买 nike

使用以下代码:

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,我认为这意味着即使我将它正确地放置在同一路径中也找不到该 View 。

最佳答案

我不确定为什么您的代码返回 null,但这在 Controller 的上下文中对我有用:

    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 作为参数。

关于c# - 找不到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com