C# 如何在mvc3中重写控制器actionresult方法?
HomeController中有一个名为Index的方法。(这只是Microsoft提供的默认模板) 现在我想要的是。。。重写索引方法。像下面这样C# 如何在mvc3中重写控制器actionresult方法?,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,HomeController中有一个名为Index的方法。(这只是Microsoft提供的默认模板) 现在我想要的是。。。重写索引方法。像下面这样 public partial class HomeController : Controller { public virtual ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!";
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设计中的开闭原则。
有没有可能?或者还有其他方法吗?A
Controller
是一个普通的C#类,因此您必须遵循正常的继承规则。如果您试图重写同一类中的方法,那是胡说八道,不会编译
public class FooController
{
public virtual ActionResult Bar()
{
}
// COMPILER ERROR here, there's nothing to override
public override ActionResult Bar()
{
}
}
如果有Foo
的子类,那么如果基类上的方法标记为virtual
,则可以重写。(而且,如果子类不重写该方法,则将调用基类上的方法。)
所以它是这样工作的:
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
您不能这样做,您正在尝试重写在同一类中声明的方法。只能重写子类中的方法。如果要“重写”同一类中的方法,只需将旧方法体替换为新方法体。如果可以,访问/home/index时会显示什么结果?@verdesmarald:假设我创建了子类。那么如何实现呢?@DannyChen:结果应该显示“覆盖索引”。表示应执行重写的方法。若要实际重写某个方法,该方法必须位于基类中。在您的示例中,
Controller
是基类,它没有名为“Index”的方法。你的意思是要重载一个方法吗?那么你的意思是说我应该创建另一个控制器并用现有的HomeController继承它?@DharmikBhandari是的,没错。那么当我请求home/index时,将调用什么方法?对于home/index
,应该调用home
中被重写的方法。
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