Я использую эти методы в своей пользовательской базе Controller
.
public string RenderPartialToString(string partialViewName, object model)
{
InvalidateControllerContext();
IView view = ViewEngines.Engines.FindPartialView(ControllerContext, partialViewName).View;
string result = RenderViewToString(view, model);
return result;
}
public string RenderViewToString(string viewName, object model)
{
InvalidateControllerContext();
IView view = ViewEngines.Engines.FindView(ControllerContext, viewName, null).View;
string result = RenderViewToString(view, model);
return result;
}
public string RenderViewToString(IView view, object model)
{
InvalidateControllerContext();
string result = null;
if (view != null)
{
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
ViewContext viewContext = new ViewContext(ControllerContext, view, new ViewDataDictionary(model), new TempDataDictionary(), writer);
view.Render(viewContext, writer);
writer.Flush();
}
result = sb.ToString();
}
return result;
}
private void InvalidateControllerContext()
{
if (ControllerContext == null)
{
ControllerContext context = new ControllerContext(System.Web.HttpContext.Current.Request.RequestContext, this);
ControllerContext = context;
}
}
Метод InvalidateControllerContext
предназначен для сценария, в котором вам нужно вручную создавать Controller
s для визуализации партиалов илипредставления вне контекста контроллера.