Frage

Perhaps I'm not calling RazorEngine in the correct place.

In my controller action I use the following code to call RazorEngine. But I think this may not be correct as when it calls through to .Execute() and then into MVC's GetActionCache() the HttpContextBase.Items fails with a "method not implemented" exception.

Am I calling RazorEngine in the wrong way? @Html.LabelFor() works fine.

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);
        }
War es hilfreich?

Lösung

powercat97 over on the github issues page has a workaround for an issue that addresses this. https://github.com/Antaris/RazorEngine/issues/46

The reason I've had much trouble is that there is no context set. Creating a new ViewContext is not sufficient. Therefore by calling a view that in turn calls our RazorEngine code via RenderAction() we get the context and the MVC framework has everything it needs when it is called by RazorEngine.

Using the AccountController as an example (HtmlTemplateBase comes from RazorEngine issues with @Html and http://www.haiders.net/post/HtmlTemplateBase.aspx):

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;
    }

and in Test.cshtml:

@model TestRazorEngine.Models.LocalPasswordModel
@{ Html.RenderAction("TestTemplate", new { vm = Model }); }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top