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 ?
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.If you have subclasses of
Foo
, then you can override, if the method on the base class is markedvirtual
. (And, if the subclass doesn't override the method, then the method on the base class will get invoked.)So it works like this: