2014-02-18 38 views
5

我無法在沒有控制器類的情況下使用「RenderPartialViewToString」。C#渲染不帶控制器的局部視圖

我目前不得不在應用程序啓動時創建HTML,這需要製作模型,製作視圖並將視圖轉換爲HTML字符串。

在我看來,它使用的HTML Helper函數/擴展,似乎只有在那裏,如果有控制器。

任何人都可以闡明我如何做到這一點?

回答

4

現在已棄用Razor.Parse。剃刀引擎的3.5版本,你會遵循的步驟此處概述: https://antaris.github.io/RazorEngine/Upgrading.html

下面的文本是逐字從上面的鏈接複製:當modeltype已知或者你

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) 

或(當你想偷懶編譯,就像解析)

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

你不能沒有電流控制器context.Try使用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('/')); 
    } 
} 

第一種方法使用剃刀引擎庫。第二個工作與控制器環境。

+0

不能reoslve符號 「剃刀」 在 「Razor.Parse」 – LmC

+5

下載剃刀引擎庫。 – user3257812

+0

從Nuget'Install-Package RazorEngine'或訪問他們的頁面https://github.com/Antaris/RazorEngine – Jimbo

0

一個很漂亮的回答這個問題是Westwind.Web.Mvc.ViewRenderer

說明: 如果您想渲染MVC以外的視圖,您需要完全可用的ControllerContext,並且Razor可以從中獲取所有信息。

通過使用視圖解析器類,你纔可以調用此方法通過傳遞模型和視圖數據字典視圖渲染:

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

我希望這會有所幫助。

享受:)

+0

EmptyController包含在ViewRenderer.cs源文件中。可以刪除。 – pixparker

+0

您需要'HttpContext.Current'才能爲ViewRenderer提供完整的功能值。當控制器在Web服務器中運行時,您可以使用它很長時間。對於單元測試(沒有web服務器和HttpContext.Current == null),我試圖解決它,但總是以相同的NullReferenceException深入MVC代碼沒有進一步的信息。相反,我最終使用了RazorEngine,因爲它在有和沒有HttpContext的情況下都有效。 – Manfred

+0

@Manfred謝謝。我有與空HttpContext相同的問題。你有RazorEngine的工作示例鏈接嗎? – pixparker