无法找到视图

时间:2014-04-11 15:12:14

标签: c# asp.net-mvc viewengine

使用以下代码:

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,我相信即使我把它正确地放在同一条路径中也找不到视图。

2 个答案:

答案 0 :(得分:1)

我不确定为什么你的代码返回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作为参数输入。

答案 1 :(得分:-1)

可能找不到您的视图,请确保将视图放置在同名文件夹中, 像这样的东西 找到“日志”视图:

  • 视图文件夹
    • 日志文件夹
      • logs.cshtml文件