【问题标题】:How to override controller actionresult method in mvc3?如何覆盖 mvc3 中的控制器 actionresult 方法?
【发布时间】:2012-09-27 22:35:46
【问题描述】:

HomeController 中有一种方法叫做 Index。 (只是微软提供的默认模板)

 public class HomeController : Controller
    {

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }

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

现在我想要的是...覆盖 Index 方法。如下所示。

public partial class HomeController : Controller
    {

        public virtual ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }

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

        public override ActionResult Index()
        {
            ViewBag.Message = "Override Index";
            return View();
        }

    }

我不希望对现有方法进行任何修改,例如 OO 设计中的 Open-Closed 原则。 有没有可能?还是有其他方法?

【问题讨论】:

  • 你不能那样做,你试图覆盖在同一个类中声明的方法。你只能覆盖子类中的方法。如果您想“覆盖”同一个类中的方法,只需将旧方法体替换为新方法体即可。
  • 如果可以的话,访问/home/index时的显示结果是什么?
  • @verdesmarald:假设我已经创建了子类。那么如何实现呢?
  • @DannyChen :结果应显示“覆盖索引”。表示应该执行被覆盖的方法。
  • 要真正重写一个方法,该方法必须在基类中。在您的示例中,Controller 是没有称为“索引”的方法的基类。您的意思是要重载一个方法吗?

标签: c# asp.net-mvc-3


【解决方案1】:

Controller 是一个普通的 C# 类,所以你必须遵循普通的继承规则。如果你试图覆盖同一个类中的方法,那是无稽之谈,不会编译。

public class FooController
{
    public virtual ActionResult Bar()
    {
    }

    // COMPILER ERROR here, there's nothing to override
    public override ActionResult Bar()
    {
    }
}

如果您有Foo 的子类,那么如果基类上的方法标记为virtual,则可以覆盖。 (而且,如果子类不覆盖该方法,则将调用基类上的方法。)

public class FooController
{
    public virtual ActionResult Bar()
    {
        return View();
    }
}

public class Foo1Controller : FooController
{
    public override ActionResult Bar()
    {
        return View();
    }
}

public class Foo2Controller : FooController
{
}

所以它是这样工作的:

Foo1 foo1 = new Foo1();
foo1.Bar();               // here the overridden Bar method in Foo1 gets called
Foo2 foo2 = new Foo2();
foo2.Bar();               // here the base Bar method in Foo gets called

【讨论】:

  • 所以你的意思是说我应该创建另一个控制器并用现有的 HomeController 继承它?
  • @DharmikBhandari 是的,完全正确。
  • 那么当我请求 home/index 时会调用什么方法?
  • 对于home/index,应该调用Home 中的覆盖方法。
猜你喜欢
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多