I'm using the RazorEngine without the MVC-Framework. That means I don't have the HtmlHelper for creating templates.
That's fine, I don't need any methods from it anyway. But I need to create my own methods like the BeginForm.
Now those are done with HtmlHelper.ViewContext.Writer.Write, which I don't have. Is there a "out of the box"-way to do that, or do I have to do some magic here?
The RazorEngine is designed with deriving your own types for use in the Engine itself.
First create your own Helpers:
public class RazorHtmlHelper
{
public IEncodedString Partial(string viewName)
{
ITemplate template = RazorEngine.Razor.Resolve(viewName);
ExecuteContext ec = new ExecuteContext();
RawString result = new RawString(template.Run(ec));
return result;
}
}
public class RazorUrlHelper
{
public string Encode(string url)
{
return System.Uri.EscapeUriString(url);
}
}
Next create your own Template:
public class RazorTemplateBase<T> : TemplateBase<T>
{
private RazorUrlHelper _urlHelper = new RazorUrlHelper();
private RazorHtmlHelper _htmlHelper = new RazorHtmlHelper();
public RazorUrlHelper Url
{
get
{
return this._urlHelper;
}
}
public RazorHtmlHelper Html
{
get
{
return this._htmlHelper;
}
}
}
Before Parsing set your TemplateServiceConfiguration:
Razor.SetTemplateService(new TemplateService(
new TemplateServiceConfiguration()
{
BaseTemplateType = typeof(RazorTemplateBase<>)
};
));
result = RazorEngine.Razor.Parse(templateText, model);
Now the RazorEngine has @Html.Partial()
and @Url.Encode()
available in views.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With