[英]How to render View as String in ASP.NET CORE 1.1
我想将部分视图呈现为字符串,我搜索并找到了这篇文章:
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
StackTrace:
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
Index was out of range. Must be non-negative and less than the size of the collection.\\r\\nParameter name: index
StackTrace:
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...
我无法重现确切的错误,但我有 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();
我有同样的问题。 仔细观察后,我意识到,我在视图中使用了一个没有设置值的 ViewData。 因此出现错误“无法将 null 转换为 'bool',因为它是不可为 null 的值类型”。 检查 Null 的值,为我解决了问题并且正确生成了视图。
您需要在/Views/Shared/Comments.cshtml:line 7
处检查Viewbag/Tempdata
。
你没有从控制器发送值到视图,在这种情况下它是空的,所以为什么它会抛出运行时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.