I am using RazorEngine to parse templates from html snippets on a web page. (This is a legacy system that switching to Mvc Razor views isn't possible, so we are switching small sections over to using RazorEngine where it makes sense). There are many of questions on SO and the internet trying to get Mvc's Html and Url helpers to work with Razor engine. To get @Html
syntax to work, I've modified some code found here to add Html to the base template:
public HtmlHelper<t> Html
{
get
{
if (helper == null)
{
var writer = this.CurrentWriter; //TemplateBase.CurrentWriter
var vcontext = new ViewContext() { Writer = writer, ViewData = this.ViewData};
helper = new HtmlHelper<t>(vcontext, this);
}
return helper;
}
}
public ViewDataDictionary ViewData
{
get
{
if (viewdata == null)
{
viewdata = new ViewDataDictionary();
viewdata.TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty };
if (this.Model != null)
{
viewdata.Model = Model;
}
}
return viewdata;
}
set
{
viewdata = value;
}
}
After a lot of debugging into the Html source code I think I've managed to instantiate everything that the Html helper needs, and it runs successfully for @Html.Label
... The problem is that the resulting html is:
<label for="MyNumber">MyNumber</label>
When it obviously should be:
<label for="MyNumber">MyNumber</label>
I am stumped as to how to fix this. I was not able to find how the encoding happens when looking through the RazorEngine source. My initial thought was that the TextWriter must be encoding the value but I have not been able to confirm this. How can I get @Html.BlahFor()
to render un-escaped html?
WebViewPage
, but it could be more trouble than it is worth to figure out how to properly construct it since MVC typically would handle that. Also I will have to re-implement the RazorEngineITemplate
on this new subclass. I will continue looking to solve the original problem as I don't really know which will be more effort. – Bunkmate