C#渲染无控制器的局部视图

LmC*_*LmC 9 c# asp.net-mvc renderpartial

我在使用没有控制器类的"RenderPartialViewToString"时遇到问题.

我目前不得不在应用程序启动时创建HTML,这需要制作模型,制作视图并将视图转换为HTML字符串.

在我的视图中,它使用HTML Helper函数/扩展,如果有控制器,它似乎只存在.

任何人都可以阐明我如何做到这一点?

use*_*812 6

如果没有当前控制器上下文,则无法使用html帮助程序.请将此扩展名用于渲染视图到html

public static class RenderViewHelper
{
    public static string RenderPartialToString(string viewPath, object model)
    {
        string viewAbsolutePath = MapPath(viewPath);

        var viewSource = File.ReadAllText(viewAbsolutePath);

        string renderedText = Razor.Parse(viewSource, model);
        return renderedText;
    }

    public static string RenderPartialToString(ControllerContext context, string partialViewName, object model)
    {
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

        var viewData = new ViewDataDictionary() { Model = model };

        if (result.View != null)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                using (var output = new HtmlTextWriter(sw))
                {
                    var viewContext = new ViewContext(context, result.View, viewData, new TempDataDictionary(), output);
                    result.View.Render(viewContext, output);
                }
            }

            return sb.ToString();
        }

        return string.Empty;
    }

    public static string MapPath(string filePath)
    {
        return HttpContext.Current != null ? HttpContext.Current.Server.MapPath(filePath) : string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, filePath.Replace("~", string.Empty).TrimStart('/'));
    }
}
Run Code Online (Sandbox Code Playgroud)

第一种方法是使用razor引擎库.第二次使用控制器上下文.

  • 下载剃刀引擎库. (5认同)

Tom*_*gan 5

Razor.Parse现已弃用.使用Razor引擎版本3.5,您将按照此处列出的步骤操作:https: //antaris.github.io/RazorEngine/Upgrading.html

以下文字从上述链接逐字复制:

var result = Razor.Parse(razorTemplate, model, cache_name)
Run Code Online (Sandbox Code Playgroud)

现在要么(当模型类型已知或您想要在启动时预编译)

// Once at startup (not required when using an ITemplateManager which knows how to resolve cache_name)
Engine.Razor.AddTemplate(cache_name, razorTemplate)
// On startup
Engine.Razor.Compile(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/)

// instead of the Razor.Parse call
var result = Engine.Razor.Run(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/, model)
Run Code Online (Sandbox Code Playgroud)

或者(当你想要懒惰的编译时,比如Parse)

// Once at startup (not required when using an ITemplateManager which knows how to resolve cache_name)
Engine.Razor.AddTemplate(cache_name, razorTemplate)

// instead of the Razor.Parse call
var result = Engine.Razor.RunCompile(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/, model)
Run Code Online (Sandbox Code Playgroud)

语义等效单行将是(仅用于快速开始使用RazorEngine):

// This will just call AddTemplate for you (every time), note that the ITemplateManager has to support AddTemplate
// and it has to handle multiple calls to AddTemplate gracefully to make this work.
// The default implementation will throw an exception when you use the same cache_name for different templates.
var result = Engine.Razor.RunCompile(razorTemplate, cache_name, model.GetType() /* typeof(MyModel) or or null for 'dynamic'*/, model
Run Code Online (Sandbox Code Playgroud)


pix*_*ker 5

这个问题的一个很好的答案是Westwind.Web.Mvc.ViewRenderer。

说明:如果您想在 MVC 之外渲染视图,您需要功能齐全的 ControllerContext,并且 Razor 可以从中获取所有信息。

通过使用 ViewRenderer 类,您可以通过传递模型和视图数据字典来调用此方法来渲染视图:

    public class EmptyController : Controller { }

    public static string RenderRazorViewToString(string viewName, [Optional] object model,[Optional] ViewDataDictionary viewData)
    {
        var controller = ViewRenderer.CreateController<EmptyController>();
        controller.ViewData =viewData??new ViewDataDictionary();
        controller.ViewData.Model = model;
        var context = controller.ControllerContext;
        var html = ViewRenderer.RenderView(viewName, model, context);
        return html;
    }
Run Code Online (Sandbox Code Playgroud)

我希望这会有所帮助。

享受 :)

  • RazorEngine 目前不适用于 .NET Core 2.0;RazorLight 不能与 HTML Helpers 或 Tag Helpers 一起使用,并且 ControllerContext 不可实现,因此如果我需要安排任务,它就不起作用。所以目前看来还没有一个真正好的解决方案。 (2认同)