I need to be able to return partial view as string in my MVC app via signalR. I'm using hubs.
I'm using the following method to return a partial view string (from here):
public static string RenderPartialView(string controllerName, string partialView, object model)
{
var context = httpContextBase as HttpContextBase;
var routes = new RouteData();
routes.Values.Add("controller", controllerName);
var requestContext = new RequestContext(context, routes);
string requiredString = requestContext.RouteData.GetRequiredString("controller");
var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
var controller = controllerFactory.CreateController(requestContext, requiredString) as ControllerBase;
controller.ControllerContext = new ControllerContext(context, routes, controller);
var ViewData = new ViewDataDictionary();
var TempData = new TempDataDictionary();
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialView);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
In order for this method to work I need HttpContext.Current
therefore in my OnConnected (I noticed that this always exists) I set it like so:
public class TaskActionStatus : Hub
{
private static HttpContextBase httpContextBase;
...
public override Task OnConnected()
{
httpContextBase = new HttpContextWrapper(HttpContext.Current) as HttpContextBase;
...
and then I use it in my RenderPartialView method:
var context = httpContextBase as HttpContextBase;
This way I always have access to current HttpContext. However, I noticed that sometimes my static copy of HttpContext is null. Why is that?.
- What's the best approach here?
- Is there a way to render partial view without HttpContext?