View中的ASP.NET控制器实例为null

时间:2021-07-24 15:40:16

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? )

当我尝试从View获取HomeController时,它总是为空,为什么?是因为我使用CodeBehind(请参阅我的完整源代码为什么我的代码隐藏中的按钮单击处理程序没有被调用?)

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 个解决方案

#1


2  

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

您可以从ViewContext获取当前控制器。它有一个Controller属性:

var currentController = ViewContext.Controller;

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

如果你确定它将是HomeController,你可以投它:

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.

话虽这么说,我不确定你到底想要实现什么,为什么地球上你的观点背后有代码,但这很远很臭。

#1


2  

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

您可以从ViewContext获取当前控制器。它有一个Controller属性:

var currentController = ViewContext.Controller;

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

如果你确定它将是HomeController,你可以投它:

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.

话虽这么说,我不确定你到底想要实现什么,为什么地球上你的观点背后有代码,但这很远很臭。