合并局部视图的输出

时间:2012-09-28 02:24:04

标签: asp.net-mvc

我有局部视图,它接受客户对象并呈现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 个答案:

答案 0 :(得分: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;