Sunny
Sunny

Reputation: 4809

Merge output of partial view

I have partial view which takes customer object and renders html. For customers list, how to merge output of the partial view on server side like similar to having renderpartial with foreach loop in the view.

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

Upvotes: 1

Views: 1541

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

You could render a partial to a string using the following extension method:

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();
        }
    }
}

and then:

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

return outputhtml;

Upvotes: 1

Related Questions