Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if request is child action request before controller context is available

In a simple mvc 4 app I installed Ninject.MVC3 nuget package.

This is my controller, very basic, ISomeClass is being injected in the constructor by ninject.

public class HomeController : Controller
{
    private readonly ISomeClass _someClass;

    public HomeController(ISomeClass someclass)
    {
        _someClass = someclass;
    }

    public ActionResult Index()
    {
        return View();
    }

    [ChildActionOnly]
    public PartialViewResult MiniView()
    {
        return PartialView("miniview", _someClass.GetName());
    }
}

This is SomeClass

public class SomeClass : ISomeClass
{
    private readonly string _someName;

    public SomeClass(string someName)
    {
        _someName = someName;
    }

    public string GetName()
    {
        return _someName;
    }
}

In Index.cshtml view I have

@{ Html.RenderAction("MiniView","Home"); }

Now in NinjectWebCommon when I go to register the service I need to know if the request was a child action request or not. Like when I call Html.RenderAction. This is what I am trying but it is not working.

kernel.Bind<ISomeClass>().To<SomeClass>()
      .WithConstructorArgument("someName", c => IsChildAction(c) ? "Child" : "Nope");

IsChildAction method - Always returns false.

private static bool IsChildAction(Ninject.Activation.IContext c)
{
   var handler = HttpContext.Current.Handler;

   /*Cant do this, ChildActionMvcHandler is internal*/        
   return handler is System.Web.Mvc.Html.ChildActionExtensions.ChildActionMvcHandler;

//OR

   //This is how ControllerContext.IsChildAction gets its value in System.Web.Mvc but      
   //RouteData.DataTokens is empty for me       
   return ((MvcHandler)handler).RequestContext.RouteData.DataTokens
                              .ContainsKey("ParentActionViewContext");
}  

Any ideas if this can be done?

ps: this is not actual code, just trying something. Is this something I should definately not do? Why?

like image 938
labroo Avatar asked Mar 20 '23 12:03

labroo


1 Answers

I ended up checking if the current request has a previous handler. Seems like it is being set only on child actions.

HttpContext.Current.PreviousHandler != null && 
HttpContext.Current.PreviousHandler is MvcHandler;
like image 180
labroo Avatar answered Apr 07 '23 20:04

labroo