使用-声明中RazorEngine(不MVC中的HtmlHelper的) [英] Using-Statement in RazorEngine (without the HtmlHelper from MVC)
问题描述
我使用的是RazorEngine没有MVC-框架。 这意味着我没有HtmlHelper的创建模板。
I'm using the RazorEngine without the MVC-Framework. That means I don't have the HtmlHelper for creating templates.
这很好,我不需要从它的任何方法呢。 但我需要创建我自己的方法,如BeginForm。
That's fine, I don't need any methods from it anyway. But I need to create my own methods like the BeginForm.
现在那些已完成了HtmlHelper.ViewContext.Writer.Write,而我没有。 是否有一个开箱即用往来港澳要做到这一点,或者我要在这里做一些神奇?
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?
推荐答案
在 RazorEngine 是设计派生自己的类型在发动机本身使用。
The RazorEngine is designed with deriving your own types for use in the Engine itself.
首先创建自己的助手:
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;
}
}
}
在解析设置TemplateServiceConfiguration:
Before Parsing set your TemplateServiceConfiguration:
Razor.SetTemplateService(new TemplateService(
new TemplateServiceConfiguration()
{
BaseTemplateType = typeof(RazorTemplateBase<>)
};
));
result = RazorEngine.Razor.Parse(templateText, model);
现在的RazorEngine具有 @ Html.Partial()
和 @ Url.En code()
提供意见。
Now the RazorEngine has @Html.Partial()
and @Url.Encode()
available in views.
这篇关于使用-声明中RazorEngine(不MVC中的HtmlHelper的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!