I use a static method in a class I called
Utilities.Common
I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go:public static string RenderPartialViewToString(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.ToString();
}
}
This will work for full views as well as partial views, just change
ViewEngines.Engines.FindPartialView
to ViewEngines.Engines.FindView
.
FindView needs another parameter (
Ref : http://stackoverflow.com/questions/4692131/in-mvc3-razor-how-do-i-get-the-html-of-a-rendered-view-inside-an-action
masterName
) which you would specify null. Also I recommend saving and restoring (after rendering) controller.ViewData.Model in case the method is called on the current controller instance and model has been assigned before this call.Ref : http://stackoverflow.com/questions/4692131/in-mvc3-razor-how-do-i-get-the-html-of-a-rendered-view-inside-an-action
Comments
Post a Comment