Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

c# - How to override controller actionresult method in mvc3?

There is one method called Index in HomeController. (It is just default template provided by Microsoft)

 public class HomeController : Controller
    {

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

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

Now What I want is that... override Index method. something like below.

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();
        }

    }

I don't want any modification in existing method like Open-Closed principle in OO design. Is it possible or not? or Is there another way ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A Controller is a normal C# class, so you have to follow the normal rules of inheritance. If you're trying to override a method in the same class, that's nonsense and will not compile.

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

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

If you have subclasses of Foo, then you can override, if the method on the base class is marked virtual. (And, if the subclass doesn't override the method, then the method on the base class will get invoked.)

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

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

public class Foo2Controller : FooController
{
}

So it works like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...