如何在ASP.NET CORE 1.1中呈现视图为字符串

时间:2017-10-06 13:51:46

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

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

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

     

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...

3 个答案:

答案 0 :(得分:0)

我无法重现确切的错误,但我有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();

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

您尚未将值从控制器发送到视图,在这种情况下,该值为null,所以为什么会引发运行时错误。