1

我有部分视图,它采用客户对象并呈现 html。对于客户列表,如何在服务器端合并部分视图的输出,类似于在视图中使用渲染部分和 foreach 循环。

//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;
4

1 回答 1

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;
于 2012-09-28T06:23:23.583 回答