2

I am trying to render a partial view from a server side event (no request).

I found the following code which was able to render partial view without a controller. Render MVC PartialView into SignalR response

public static string RenderPartialView(string controllerName, string partialView, object model)
{
    var context = new HttpContextWrapper(System.Web.HttpContext.Current) as HttpContextBase;

    var routes = new System.Web.Routing.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();
    }
}

This works fine when used after a client request (SignalR/websocket), but if the code is triggered by a server-side event (WCF connection to another app), HttpContext.Current = null which causes an error.

How can I make this work?

PS. I have also tried Razor Engine but I'm getting the error "Unable to compile template. The name 'Html' does not exist in the current context". Since the template also contains "@Html", it seems that the razor engine cannot parse the template outside a controller.

Community
  • 1
  • 1
Thomasian
  • 63
  • 1
  • 4

1 Answers1

0

I was able to make it work using RazorEngine by removing all @Html tags from the partial view file.

string template = System.IO.File.ReadAllText(path);
string partialView = RazorEngine.Razor.Parse(template, model, "cachename");

http://forums.asp.net/t/1923611.aspx/2/10?Fake+HttpContext+ASP+NET+MVC+#5459457

Thomasian
  • 63
  • 1
  • 4