您可以使用以下扩展方法将部分呈现为字符串:
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;