Using-Statement in RazorEngine (without MVC's HtmlHelper)

I am using RazorEngine without MVC-Framework. This means that I do not have an HtmlHelper for creating templates.

Well, I still don't need any methods. But I need to create my own methods like BeginForm.

Now this is done with HtmlHelper.ViewContext.Writer.Write, which I do not have. Is there "out of the box" to do this, or do I need to do some magic here?

+7
razorengine
source share
1 answer

RazorEngine is designed using proprietary 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); } } 

Then 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 the TemplateServiceConfiguration template:

 Razor.SetTemplateService(new TemplateService( new TemplateServiceConfiguration() { BaseTemplateType = typeof(RazorTemplateBase<>) }; )); result = RazorEngine.Razor.Parse(templateText, model); 

RazorEngine now has @Html.Partial() and @Url.Encode() available in views.

+11
source share

All Articles