1

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;
Sunny
  • 4,765
  • 5
  • 37
  • 72

1 Answers1

1

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;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • If you get chance, could you please provide your insight on this. I had seen many validation posts on this by you, but I am not knowing how to acheive it. Thanks again..http://stackoverflow.com/questions/12613188/validate-only-ajax-loaded-partial-view/12615865#12615865 – Sunny Sep 28 '12 at 06:27