2016-06-27 172 views
0

我試圖呈現一個視圖作爲字符串被用作電子郵件模板。我目前正在努力實現這個例子: https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String渲染視圖作爲字符串

與這部分代碼但是我有困難:

public ViewRenderer(ControllerContext controllerContext = null) 
{ 
    // Create a known controller from HttpContext if no context is passed 
    if (controllerContext == null) 
    { 
     if (HttpContext.Current != null) 
      controllerContext = CreateController<ErrorController>().ControllerContext; 
     else 
      throw new InvalidOperationException(
       "ViewRenderer must run in the context of an ASP.NET " + 
       "Application and requires HttpContext.Current to be present."); 
    } 
    Context = controllerContext; 
} 

Visual Studio是給我下面的錯誤:

"The type or namespace name 'ErrorController' could not be found (are you missing a using directive or an assembly reference?)"

我大概失蹤明顯的東西,但看不到它是什麼。有任何想法嗎?

+1

你在你的項目中有一個'ErrorController'? – NightOwl888

+0

不,我不知道這是否是可以添加一個標準化的控制器,或者如果它是我必須去創造。 – HuwD

回答

5

如果你需要渲染你的看法作爲一個字符串,這裏是我寫的控制器的擴展方法。

NB:我會設法找出我曾經幫助我這個確切的鏈接,並更新我的答案,當我找到它。

Here另一個鏈路,描述這個方法。

這應該做的伎倆:

public static string RenderViewToString(this Controller controller, string viewName, object model) 
    { 
     var context = controller.ControllerContext; 
     if (string.IsNullOrEmpty(viewName)) 
      viewName = context.RouteData.GetRequiredString("action"); 

     var viewData = new ViewDataDictionary(model); 

     using (var sw = new StringWriter()) 
     { 
      var viewResult = ViewEngines.Engines.FindPartialView(context, viewName); 
      var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw); 
      viewResult.View.Render(viewContext, sw); 

      return sw.GetStringBuilder().ToString(); 
     } 
    } 

如果你想從一個控制器調用此方法,你只需做到以下幾點:

var strView = this.RenderViewToString("YourViewName", yourModel); 
+0

謝謝,需要一些小的調整來處理我的項目,但其他人完全是我需要的。 – HuwD

+0

有沒有辦法設置編碼?這工作對我的看法enlish很大,但是,我也有一些西班牙的意見(UTF-8)和所有帶重音符號的字符都呈現爲ANSI編碼,例如P ó ngase代替Póngase。我已經嘗試在web.config中設置全球化fileEncoding =「utf-8」,並且沒有任何運氣使用子類編碼的textwriter。 – alexb