Using-Statement in RazorEngine (without the HtmlHelper from MVC)

别等时光非礼了梦想. 提交于 2019-12-04 04:48:22

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!