I\'ve been happily returning JsonResult objects or partial ASP.NET views from my controllers in ASP.NET.
I would like to return a rendered partial view as a property
I was looking for a better way to do this myself because I assumed the way I was doing it was outdated. I forget where I got this and take no credit for it, but since I ended up here I figure I'll post what I use as well. Hope it helps anyone coming along looking for something newer than the answers above.
** NOTE This only addresses the rendering of the view to a string. The answers above address the question about putting the result into a property on a JSON object and the OP seemed pretty comfortable with that anyway.
public string RenderViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}