RazorLight
RazorLight copied to clipboard
viewbag not passed when using the cached template
Describe the bug ViewBag parameter is not passed the second time when template is retrieved from cache.
To Reproduce
A second call to below, gives a success
👍 in cacheResult
but unfortunately only the model
is reaching the view template when .RenderTemplateAsync<T>(cacheResult.Template.TemplatePageFactory(), model, viewBag);
is called.
dynamic viewBag = new ExpandoObject();
viewBag.One = "something";
viewBag.Two = "other something";
var cacheResult = _engine.TemplateCache.RetrieveTemplate(viewName);
string result;
if (cacheResult.Success)
{
result = await _engine
.RenderTemplateAsync<T>(cacheResult.Template.TemplatePageFactory(), model, viewBag);
}
else
{
result = await _engine
.CompileRenderAsync<T>(viewName, model, viewBag);
}
Expected behavior
A viewbag to be passed in RenderTemplateAsync
just like in .CompileRenderAsync<T>(viewRoute, model, viewBag);
, but the folowing exception is thrown, (and indeed putting a breakpoint in my view shows that ViewBag
is empty):
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500
Message='System.Dynamic.ExpandoObject' does not contain a definition for 'One'
Source=System.Linq.Expressions
Information
- OS: Windows 10
- Platform: .NET Core 2.1
- RazorLight version: 2.0.0-beta1
Additional context Add any other context about the problem here.
Problem exist on RazorLight 2.0.0-beta1 But it looks that this is already fixed in gihub, https://github.com/toddams/RazorLight/blob/master/src/RazorLight/RazorLightEngine.cs
The workaround for me was to use the other method. Instead of:
await Engine.RenderTemplateAsync(found.Template.TemplatePageFactory(), model, ViewBag);
Used
await Engine.RenderTemplateAsync(found.Template.TemplatePageFactory(), (object)model, Type.GetTypeFromHandle(typeof(T).TypeHandle), ViewBag);
This is specific per nugget package, I see that on source code these two methods are obsolete. Checking decompiled Assembly, it looks like optional parameter ExpandoObject viewBag = null is not passed to next invocation if present, value sent is plain null.