0

When I try to get HomeController from View, it's always null, why ? Is it because I use CodeBehind (see my full source code Why my button click handler in codebehind is not called? )

public partial class Index : System.Web.Mvc.ViewPage<dynamic>
    {


        HomeController HomeController;



        protected void Page_Load(object sender, EventArgs e)
        {

            HomeController = (HomeController)HttpContext.Current.Request.RequestContext.RouteData.Values["HomeController"];

1 Answer 1

2

You could get the current controller from the ViewContext. It has a Controller property:

var currentController = ViewContext.Controller;

and if you know for sure that it's gonna be HomeController you could cast it:

var homeController = (HomeController)ViewContext.Controller;

This being said, I am not sure what exactly are you trying to achieve and why on Earth does your view has code behind, but this stinks from very far.

Sign up to request clarification or add additional context in comments.

2 Comments

Totally agreed here with @DarinDimitrov. It makes no sense what you are trying to do. This is not MVC and is webforms but also webforms don't have a concept of a controller. why are you trying to reinvent the wheel or make something so complicated and difficult to maintain and follow through?
@DarinDimitrov I'm just trying to understand all the internals of ASP.NET MVC at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.