0

MVC3でコントローラーを呼び出すために使用するカスタムIHttpHandlerがあります。問題は、View( "〜/ path / to / my / view.cshtml")を呼び出しても何も得られないことです。エラーはありません。何もありません。ソースが空で、200okです。

これを自分自身と呼んでいるので、ビューのライフサイクルの一部が開始されていないのでしょうか。

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();
    }

コントローラからのコード:

    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>
4

1 に答える 1

0

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);
于 2012-07-24T10:55:45.640 に答える