Reputation: 4840
I have the following code:
public string View(string view, object model)
{
var template = File.ReadAllText(HttpContext.Current.Request.MapPath(@"~\Views\PublishTemplates\" + view + ".cshtml"));
if (model == null)
{
model = new object();
}
return RazorEngine.Razor.Parse(template, model);
}
and I'm using the following view
@model NewsReleaseCreator.Models.NewsRelease
@{
Layout = "~/Views/Shared/_LayoutBlank.cshtml";
}
@Model.Headline
I am getting:
[NullReferenceException: Object reference not set to an instance of an object.] RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context) in c:\Users\Matthew\Documents\GitHub\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateBase.cs:139
If I remove the Layout Line it works fine
My Layout
<!DOCTYPE html>
<html>
<head>
@RenderSection("MetaSection", false)
<title>@ViewBag.Title</title>
@RenderSection("HeaderSection", false)
</head>
<body>
@RenderBody()
</body>
</html>
Thoughts?
Upvotes: 6
Views: 4847
Reputation: 4840
I ended up not using Razor Engine
My solution does require a controller context so I just use the one from the Controller that was called. So in my controller
InstanceOfMyClass.ControllerCurrent = this
And in MyClass
public string RenderViewToString(string viewName, object model, string layoutName)
{
ControllerCurrent.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerCurrent.ControllerContext, viewName, layoutName);
ViewContext viewContext = new ViewContext(ControllerCurrent.ControllerContext, viewResult.View, ControllerCurrent.ViewData, ControllerCurrent.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
Upvotes: 0
Reputation: 1898
I looked sources of TemplateBase.cs (https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateBase.cs):
line 139: return layout.Run(context);
NullReferenceException possibe, if 'layout' variable is null. Ok, what is 'layout'?
line 133: var layout = ResolveLayout(Layout);
Go deeper (https://github.com/Antaris/RazorEngine/blob/master/src/Core/RazorEngine.Core/Templating/TemplateService.cs):
public ITemplate Resolve(string cacheName, object model)
{
CachedTemplateItem cachedItem;
ITemplate instance = null;
if (_cache.TryGetValue(cacheName, out cachedItem))
instance = CreateTemplate(null, cachedItem.TemplateType, model);
if (instance == null && _config.Resolver != null)
{
string template = _config.Resolver.Resolve(cacheName);
if (!string.IsNullOrWhiteSpace(template))
instance = GetTemplate(template, model, cacheName);
}
return instance;
}
And, i see here, that NullReference is possible, if _config.Resolver is null. Check your Resolver.
Upvotes: 3