【发布时间】: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.<ExecuteAsync>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