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

时间:2014-02-18 13:19:59

标签: c# asp.net-mvc renderpartial

我在使用没有控制器类的“RenderPartialViewToString”时遇到问题。

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

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

任何人都可以了解我如何做到这一点吗?

2 个答案:

答案 0 :(得分: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('/'));
    }
}

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

答案 1 :(得分:5)

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

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

var result = Razor.Parse(razorTemplate, model, cache_name)

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

// 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)

或(当你想要延迟编译时,比如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)

语义等效单行将是(仅用于快速开始使用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