How to render View as String in ASP.NET CORE 1.1

I want to render partial view as string and i searched and found this article:

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();
    }
}

but inner error happen:

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

The error with me is in innerException, and I cannot know exactly what is the reason, but i think in that line of code:

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

I check line 7 in the view and found some variable not has value and fixed it, but another error appear:

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

I cannot reproduce the exact error but I have 2 suggestions:

1. Check viewResult is NULL or not first

The viewResult might be NULL hence viewResult.View might throw NullReferenceException. So I would do:

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

2. await on 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();

Render Razor View to string in ASP.NET Core, UPDATE July, 2016. Working fine on the following versions 1.0.0 , RC2. Who's targeting aspnetcore RC2, this snippet might help you: Create a separate Service ,� Sometimes you may need to render a certain view as string, for example when you want to send an email where usually the body is pure html. To do so, you need to create a service that takes two arguments: the first one is a string representing the path to the view you want to render; the second one is an object that is used from the view.

I had the same issue. After looking at this closer, I realized, that I had used a ViewData in the View, that had no value set. Hence the error "Cannot convert null to 'bool' because it is a non-nullable value type". Checking the value for Null, solved the issue for me and the view generated correctly.

ASP.NET Core Render View to String – Paris Polyzos' blog, Mvc.ViewFeatures;. using Microsoft.AspNetCore.Routing;. namespace Project. Utilities. {. public interface IViewRenderService. {. Task<string>� How is it possible to render a Razor view to a string, while using the new Razor pre-compilation from ASP.NET Core 1.1? The following code is from the example and the exception will be thrown because viewResult.View is null.

You need to check Viewbag/Tempdata at /Views/Shared/Comments.cshtml:line 7.

You have not send value from controller to view, in this case it's null so why it's throw the runtime error.

Generate a HTML string from cshtml razor view using ASP.NET Core , asp.net-core .net html c# viewtostring renderview render-view-as-string Use cases for rendering an HTML string from a cshtml razor view. Render Razor View to string in ASP.NET Core. Ask Question With ASP.NET Core 1.1.0 I was having an issue that went away when I started using the version here:

c#: How to render View as String in ASP.NET CORE 1.1, I want to render partial view as string and i searched and found this� Caching. RazorEngineCore is not responsible for caching. Each team and project has their own caching frameworks and conventions therefore making it impossible to have builtin solution for all possible needs.

View components in ASP.NET Core, For ASP.NET Core 1.1 and higher, you can invoke a view component as string MyView = "Default"; // If asking for all completed tasks, render� To render a component from a page or view, use the Component Tag Helper. Prerequisites Follow the guidance in the Prepare the app to use components in pages and views section of the Integrate ASP.NET Core Razor components into Razor Pages and MVC apps article.

How to: Render ASP.NET MVC Razor Views to Strings, ASP.NET MVC and the Razor Engine that is used to render ASP.NET MVC views MVC Razor views directly to string in order to capture the output and to render It provides only the core language and HTML parsing services, and none of� For more information, see Create and use ASP.NET Core Razor components. Creating a view component. This section contains the high-level requirements to create a view component. Later in the article, we'll examine each step in detail and create a view component. The view component class. A view component class can be created by any of the following:

Comments
  • Could you please show your code, the error message says that you're trying to set null to a Boolean, because bool is non-nullable.
  • my code is exactly as the example in the link, but the error with me is in innerException, and i cannot know exactly what is the reason, but i think in that line of code : var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw, new HtmlHelperOptions() );
  • Your view has an error in it on line 7.
  • CodeCaster, yes i fixed it but another error appear, i update my post
  • viewResult in not null, i checked it, and i used await as you said but another error appear after fix the first error, i update my post
  • I have the exactly same code beside the checking viewResult vs viewResult.View. And mine runs fine. Did you put your templates under Views/Shared folder?
  • yes, Comments.cshtml template is in the shared folder, i checked the viewResult.View.Path by using Break points in debugging it is: "Views/Shared/Comments.cshtml" .... but i want to know which Index it mean in the last error appears?
  • awww without debuging in the souce code, its hard to know where the error comes from.