2010-04-11 91 views
0

我需要呈現部分視圖到控制器操作中的字符串。我有以下示例代碼,但ControllerContext。 ParentActionViewContext似乎沒有在MVC 1.0asp.net mvc 1.0 - 如何將部分視圖呈現爲字符串

  // Get the IView of the PartialView object. 
      var view = PartialView("MyPartialView").View; 

      // Initialize a StringWriter for rendering the output. 
      var writer = new StringWriter(); 

      // Do the actual rendering. 
      view.Render(ControllerContext.ParentActionViewContext, writer); 

不勝感激任何提示存在。

+0

http://stackoverflow.com/questions/2537741/how-to-render-partial-view-into-a-string – Jarek 2010-04-11 11:20:11

回答

1

嘗試此MVC 1.0(,我使用的擴展方法)

public static class Extensionmethods 
{ 
    public static string RenderPartialToString(this Controller controller, string partialName) 
    { 
     return RenderPartialToString(controller, partialName, new object()); 
    } 
    public static string RenderPartialToString(this Controller controller, string partialName, object model) 
    { 
     var vd = new ViewDataDictionary(controller.ViewData); 
     var vp = new ViewPage 
     { 
      ViewData = vd, 
      ViewContext = new ViewContext(), 
      Url = new UrlHelper(controller.ControllerContext.RequestContext) 
     }; 

     ViewEngineResult result = ViewEngines 
            .Engines 
            .FindPartialView(controller.ControllerContext, partialName); 

     if (result.View == null) 
     { 
      throw new InvalidOperationException(
      string.Format("The partial view '{0}' could not be found", partialName)); 
     } 
     var partialPath = ((WebFormView)result.View).ViewPath; 

     vp.ViewData.Model = model; 

     Control control = vp.LoadControl(partialPath); 
     vp.Controls.Add(control); 

     var sb = new StringBuilder(); 

     using (var sw = new StringWriter(sb)) 
     { 
      using (var tw = new HtmlTextWriter(sw)) 
      { 
       vp.RenderControl(tw); 
      } 
     } 
     return sb.ToString(); 
    } 
} 

用法:

.... 
string htmlBlock = this.RenderPartialToString("YourPartialView", model); 
return htmlBlock; 

我使用此一噸100%的成功控制器...

jim