1

我想渲染一個RazorView字符串,但在果園CMS,但我不知道如何獲得鏈接到部分視圖來獲取字符串。獲取鏈接到部分視圖在果園CMS

public string RenderRazorViewToString(string viewName, object model) 
     { 
      ViewData.Model = model; 
      using (var sw = new StringWriter()) 
      { 
       var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); 
       var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); 
       viewResult.View.Render(viewContext, sw); 
       viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); 
       return sw.GetStringBuilder().ToString(); 
      } 
     } 

如果在另一個MVC項目 - 不果園 - 它的工作確定的代碼:

string result = RenderRazorViewToString("~/Views/Home/PartialViewEmail.cshtml", null); 

但在果園CMS,它不知道從哪裏得到這partialview。

我該怎麼辦?

非常感謝!

回答

0

我已經解決了這個問題。這很簡單,就像下面那樣

PartialViewResult path = PartialView("PartialViewEmail"); 
string tmp = path.ViewName; 
string result = RenderRazorViewToString(tmp, null); 
5

然而更好的解決方法是採用烏節路的做事方式,使用形狀。如果你這樣做:

@Display.ViewEmail(SomeParameter: 42, SomeOtherParameter: "foo") 

然後/Views命名ViewEmail.cshtml下創建您的主題文件,你可以參考傳過來的Model屬性,如果你需要它們的參數。致電Display將導致ViewEmail形狀的渲染。

0

我選擇了類似下面的擴展方法:

public static class ViewExtensions 
{ 
    public static string RenderToString(this PartialViewResult partialView) 
    { 
     var httpContext = HttpContext.Current; 

     if (httpContext == null) 
     { 
      throw new NotSupportedException("An HTTP context is required to render the partial view to a string"); 
     } 

     var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString(); 

     var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory().CreateController(httpContext.Request.RequestContext, controllerName); 

     var controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller); 

     var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View; 

     var sb = new StringBuilder(); 

     using (var sw = new StringWriter(sb)) 
     { 
      using (var tw = new HtmlTextWriter(sw)) 
      { 
       view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw); 
      } 
     } 

     return sb.ToString(); 
    } 
} 

它能讓我做到以下幾點:

var html = PartialView("SomeView").RenderToString(); 

如果我仍然想獲得視圖的完整路徑由於某種原因,我可以做到以下幾點:

var path = ((BuildManagerCompiledView)view).ViewPath; // Will be something like "~/Views/Shared/SomeView.cshtml"