Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor engine cant find view

I'm trying to render a HTML from a view without using a web request. I need the HTML as a string, internally, I do not wish to serve it.

The viewEngine.FindView() returns a viewEnineResult that shows no view was found. It shows to search locations where it looked they look like this:

/Views//PDFOperationsReportView.cshtml

/Views/Shared/PDFOperationsReportView.cshtml

(Observe the double forward slash in the first line)

File structure (I placed it into a HTML snippet cause I couldn't manage to format the text properly in this editor)

Project 
      Folder 
        Subfolder
            CodeFile.cs
      Views
        PDFOperationsReportView.cshtml

The code:

var viewName = "PDFOperationsReportView";
var actionContext = GetActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);
if (!viewEngineResult.Success)
{
    throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
}
            
var view = viewEngineResult.View;
like image 556
Daarwin Avatar asked May 16 '17 08:05

Daarwin


People also ask

How does a Razor view engine work?

Web Form Engine has the same syntax like Asp.net Web Forms uses for . aspx pages. By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view. Razor Engine is little bit slow as compared to Webform Engine.

What is meant by view in net?

A view is an HTML template with embedded Razor markup. Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.

What is razor engine in ASP NET MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.


1 Answers

I had the same issue. I found the answer here: GitHub aspnet/Mvc Issue #4936

Basically, use GetView instead of FindView, like this:

var viewResult = razorViewEngine.GetView(viewName, viewName, false);

Your viewName needs to be a full path for this to work. For example:

  1. /Views/Shared/PDFOperationsReportView.cshtml
  2. ~/Pages/Shared/_Article.cshtml
  3. ~/Areas/CM/Pages/_Article.cshtml
like image 101
Matt Avatar answered Oct 07 '22 00:10

Matt