【问题标题】:How to render View as String in ASP.NET CORE 1.1如何在 ASP.NET CORE 1.1 中将视图呈现为字符串
【发布时间】:2019-12-13 14:34:40
【问题描述】:

我想将部分视图呈现为字符串,我搜索并找到了这篇文章:

https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string

public async Task<string> RenderToStringAsync(string viewName, object model)
{
    var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
    var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

    using (var sw = new StringWriter())
    {
        var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

        if (viewResult.View == null)
        {
            throw new ArgumentNullException($"{viewName} does not match any available view");
        }

        var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
        {
            Model = model
        };

        var viewContext = new ViewContext(
            actionContext,
            viewResult.View,
            viewDictionary,
            new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
            sw,
            new HtmlHelperOptions()
        );

        await viewResult.View.RenderAsync(viewContext);

        return sw.ToString();
    }
}

但发生内部错误:

留言:Cannot convert null to 'bool' because it is a non-nullable value type

堆栈跟踪:at CallSite.Target(Closure , CallSite , Object )\r\n at CallSite.Target(Closure , CallSite , Object )\r\n at AspNetCore._Views_Shared_Comments_cshtml.&lt;ExecuteAsync&gt;d__39.MoveNext() in /Views/Shared/Comments.cshtml:line 7\r\n--- End of stack trace fr...

我的错误是innerException,我无法确切知道是什么原因,但我认为在那行代码中:

var viewContext = new ViewContext(
    actionContext,
    viewResult.View,
    viewDictionary,
    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
    sw,
    new HtmlHelperOptions()
);

我查看视图中的第 7 行,发现一些变量没有值并修复它,但出现另一个错误:

留言:Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index

堆栈跟踪:at System.ThrowHelper.ThrowArgumentOutOfRange_IndexException()\r\n at System.Collections.Generic.List``1.get_Item(Int32 index)\r\n at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values)\r\n a...

【问题讨论】:

  • 能否请您出示您的代码,错误消息表明您正在尝试将null 设置为布尔值,因为布尔值不可为空。
  • 我的代码与链接中的示例完全相同,但我的错误在 innerException 中,我无法确切知道是什么原因,但我认为在那行代码中:var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw, new HtmlHelperOptions());
  • 您的视图在第 7 行有错误。
  • CodeCaster,是的,我修复了它,但出现了另一个错误,我更新了我的帖子

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

我无法重现确切的错误,但我有 2 条建议:

1.首先检查viewResult 是否为NULL

viewResult 可能是 NULL,因此 viewResult.View 可能会抛出 NullReferenceException。所以我会这样做:

if (viewResult == null)
{
    throw new ArgumentNullException($"{ viewname } is not found.");
}

2。 await View.RenderAsync()

var viewContext = new ViewContext(actionContext,
    viewResult.View,
    viewDictionary,
    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
    sw,
    new HtmlHelperOptions()
);

await viewResult.View.RenderAsync(viewContext);

return sw.ToString();

【讨论】:

  • viewResult in not null,我检查了它,我用了你说的 await 但修复第一个错误后出现另一个错误,我更新我的帖子
  • 我在检查 viewResult 与 viewResult.View 旁边有完全相同的代码。我的运行良好。您是否将模板放在 Views/Shared 文件夹下?
  • 是的,Comments.cshtml 模板在共享文件夹中,我在调试时使用断点检查了 viewResult.View.Path,它是:“Views/Shared/Comments.cshtml”...。但我想知道最后一个错误中出现的索引是什么?
  • awww 没有在源代码中调试,很难知道错误来自哪里。
【解决方案2】:

我有同样的问题。仔细观察后,我意识到我在 View 中使用了一个 ViewData,它没有设置任何值。因此出现错误“无法将 null 转换为 'bool',因为它是不可为空的值类型”。检查 Null 的值,为我解决了这个问题,并正确生成了视图。

【讨论】:

    【解决方案3】:

    您需要检查Viewbag/Tempdata/Views/Shared/Comments.cshtml:line 7

    你还没有从控制器发送值到视图,在这种情况下它是空的,所以为什么它会抛出运行时错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 2021-06-16
      • 2015-08-02
      相关资源
      最近更新 更多