2012-09-28 105 views
1

我有部分視圖,它接受客戶對象並呈現html。對於客戶列表,如何在服務器端合併部分視圖的輸出,類似於在視圖中使用foreach循環呈現renderpartial。合併部分視圖的輸出

//how to write action method for below 
foreach(var item in customerslist) 
{ 
//get html by calling the parview 
outputhtml += //output from new _partialviewCustomer(item); 
} 

return outputhtml; 

回答

1

你可以使用下面的擴展方法渲染的部分轉換爲字符串:

public static class HtmlExtensions 
{ 
    public static string RenderPartialViewToString(this ControllerContext context, string viewName, object model) 
    { 
     if (string.IsNullOrEmpty(viewName)) 
     { 
      viewName = context.RouteData.GetRequiredString("action"); 
     } 

     context.Controller.ViewData.Model = model; 

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

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

然後:

foreach(var item in customerslist) 
{ 
//get html by calling the parview 
outputhtml += ControllerContext.RenderPartialViewToString("~/Views/SomeController/_Customer.cshtml", item) 
} 

return outputhtml; 
+0

如果你得到機會,你可以請提供您對此的見解。我已經看到過很多驗證帖子,但我不知道如何實現它。再次感謝..http://stackoverflow.com/questions/12613188/validate-only-ajax-loaded-partial-view/12615865#12615865 – Sunny