Last post Jan 02, 2021 06:51 PM by mgebhard
Jan 02, 2021 03:56 PM|kobruleht|LINK
Looking to render Razor views in code. Views use @HTml. extensions.
Tried to use https://github.com/wdcossey/RazorEngineCore.Extensions which should add this feature to RazorEngineCore :
tOrAdd(templateHashCode, i =>
(IRazorEngineCompiledTemplate<RazorEngineCorePageModel<TModel>>)TemplateCache.GetOrAdd(templateHashCode, i =>
var razorEngine = new RazorEngine();
var compiledTemplate = razorEngine.Compile<RazorEngineTemplateBase<TModel>>(template, builder =>
but got exception
An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'RazorEngineCore.RazorEngineCompiledTemplate1[RazorEngineCore.RazorEngineTemplateBase1[System.Object]]' to type 'RazorEngineCore.IRazorEngineCompiledTemplate1[RazorEngineCore.RazorEngineCorePageModel1[System.Object]]'.
Original template (which does not have @Html support):
var compiledTemplate = (IRazorEngineCompiledTemplate<RazorEngineTemplateBase<TModel>>)TemplateCache.GetOrAdd(templateHashCode, i =>
works but @Html and other extensions cause error.
How to use @Html and other extensions in compiled Razor templates in ASP.NET MVC Core 6 ?
Jan 02, 2021 04:26 PM|mgebhard|LINK
Maybe you are looking for reusable UI (Razor Class Library) support in Core?
Jan 02, 2021 05:12 PM|bruce (sqlwork.com)|LINK
The library has its own implementation of the HtmlHelper:
you would need to modify this class to have more features.
Jan 02, 2021 05:28 PM|kobruleht|LINK
I tried to use this library, RazorEngineCore.Extensions
in unmodified form but got casting excaption as described.
It provides generic Template base class which adds Html method implementation.
This class is based on RazorEngineCore generic template class which works.
Why casting to parent class throws cast exception ? Casting to parent class in class hiearachy should work.
Maybe something is changed in in C# 9 or .NET 5 which caused this runtime exception.
Jan 02, 2021 06:24 PM|kobruleht|LINK
No. According to
this may caused by the way how C#9 handles covariant types. Cache object type in code is set to object to avoid this, but exception still occurs.
Jan 02, 2021 06:51 PM|mgebhard|LINK
As far as I can tell, you are casting a base type to a derived type. This is not possible nor has it ever been possible in C#. Rather, pass the base class to the derived class's constructor. There's also extension methods.