View called from controller using IHttpHandler returning nothing

I have a custom IHttpHandler that im using to call my controller in MVC3. Problem is that when I call View("~/path/to/my/view.cshtml") I get nothing. No error. Nothing, just empty source and a 200 ok.

Since im calling this my self is there some part of the view life-cycle that's not getting started?

IHttpHandler:

public class MyHttpHandler : IHttpHandler
{
    ISimpleController _c;

    public SimpleHttpHandler(Controller c)
    {
        _c = c;
    }

    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        _c.Get();
    }

Code from controller:

    public new ActionResult Get()
    {
        ViewBag.Proof = "Ping";
        ViewBag.Of = "Pong";
        ViewBag.Life = "Fizz";
        return View("~/Views/Shared/WhatAView.cshtml");
    }

WhatAView.cshtml:

<ul>
@foreach(var pair in ViewData)
{
   <li>@pair.Key : @pair.Value</li>
}
</ul>

Answers


The only thing you need is to call ExecuteResult() on your ActionResult. This will force rendering of your view. This is what MVC Framework does after it retrieves ActionResult from a controller.

_c.Get().ExecuteResult(_c.ControllerContext);

It's important that you implemented controller properly w/ valid ControllerContext. I have decompiled ViewResultBase.ExecuteResult() using dotPeek:

public override void ExecuteResult(ControllerContext context)
{
  if (context == null)
    throw new ArgumentNullException("context");
  if (string.IsNullOrEmpty(this.ViewName))
    this.ViewName = context.RouteData.GetRequiredString("action");
  ViewEngineResult viewEngineResult = (ViewEngineResult) null;
  if (this.View == null)
  {
    viewEngineResult = this.FindView(context);
    this.View = viewEngineResult.View;
  }
  TextWriter output = context.HttpContext.Response.Output;
  this.View.Render(new ViewContext(context, this.View, this.ViewData, this.TempData, output), output);
  if (viewEngineResult == null)
    return;
  viewEngineResult.ViewEngine.ReleaseView(context, this.View);
}

You see that this method renders the view into ControllerContext.HttpContext. Ensure that HttpContext is avalaible from within your controller.

As seen above you still can use raw rendering:

  TextWriter output = context.HttpContext.Response.Output;
  var viewResult = (ViewResult)_c.Get();
  viewResult.View.Render(new ViewContext(_c.ControllerContext, viewResult.View, viewResult.ViewData, viewResult.TempData, output), output);

Need Your Help

Open my mobile Java program with SMS, no SMS in inbox

java mobile sms

Is it possible to open my mobile Java program with an SMS?

google search results in iframe alternative

search iframe lightbox

I don't think it's possible from what I've read, but wanted to see if anyone else was in a similar situation and found a more elegent solution to this problem.