Asp.net mvc 在控制器操作中调用RazorEngine.Parse()失败,HttpContextBase错误
也许我给RazorEngine打电话的地方不对 在我的控制器操作中,我使用以下代码调用RazorEngine。但我认为这可能不正确,因为当它调用.Execute()然后调用MVC的GetActionCache()时,HttpContextBase.Items失败,出现“method not implemented”异常 我打错电话给RazorEngine了吗@LabelFor()工作正常Asp.net mvc 在控制器操作中调用RazorEngine.Parse()失败,HttpContextBase错误,asp.net-mvc,razorengine,Asp.net Mvc,Razorengine,也许我给RazorEngine打电话的地方不对 在我的控制器操作中,我使用以下代码调用RazorEngine。但我认为这可能不正确,因为当它调用.Execute()然后调用MVC的GetActionCache()时,HttpContextBase.Items失败,出现“method not implemented”异常 我打错电话给RazorEngine了吗@LabelFor()工作正常 string template = "@Html.EditorFor(model => model.O
string template = "@Html.EditorFor(model => model.OldPassword)";
string result = string.Empty;
var config = new RazorEngine.Configuration.TemplateServiceConfiguration
{
BaseTemplateType = typeof(System.Web.Mvc.Helpers.HtmlTemplateBase<>)
};
using (var service = new RazorEngine.Templating.TemplateService(config))
{
// Use template service.
RazorEngine.Razor.SetTemplateService(service);
result = RazorEngine.Razor.Parse(template, model);
}
string template=“@Html.EditorFor(model=>model.OldPassword)”;
字符串结果=string.Empty;
var config=new RazorEngine.Configuration.TemplateServiceConfiguration
{
BaseTemplateType=typeof(System.Web.Mvc.Helpers.HtmlTemplateBase)
};
使用(var service=new RazorEngine.Templating.TemplateService(config))
{
//使用模板服务。
RazorEngine.Razor.SetTemplateService(服务);
result=RazorEngine.Razor.Parse(模板、模型);
}
github问题页面上的powercat97有一个解决此问题的方法。
我遇到很多麻烦的原因是没有上下文设置。创建新的ViewContext是不够的。
因此,通过调用一个视图,然后通过RenderAction()调用我们的RazorEngine代码,我们得到了上下文,MVC框架在被RazorEngine调用时拥有了它所需要的一切
以AccountController为例(HtmlTemplateBase来自和):
public ActionResult Test()
{
var model = new MySite.Models.LocalPasswordModel();
model.OldPassword = "MyOldPwd";
model.NewPassword = "SomeNewPwd";
return PartialView(model);
}
[ChildActionOnly()]
public string TestTemplate(MySite.Models.LocalPasswordModel vm)
{
string result = string.Empty;
string template = "@Html.EditorFor(model => model.OldPassword)";
var config = new RazorEngine.Configuration.TemplateServiceConfiguration
{
BaseTemplateType = typeof(HtmlTemplateBase<>)
};
using (var service = new RazorEngine.Templating.TemplateService(config))
{
// Use template service.
RazorEngine.Razor.SetTemplateService(service);
result = RazorEngine.Razor.Parse(template, vm, "MyTemplateName");
}
return result;
}
@model TestRazorEngine.Models.LocalPasswordModel
@{ Html.RenderAction("TestTemplate", new { vm = Model }); }