This blog will go over how to overload the MVC action method. Let me demonstrate with a simple MVC application.
I have created an MVC application and added the controller to it. I’d like to use polymorphism in this controller. I added two action methods with the same name but different parameters to the same controller.
public ActionResult GetCustomers() { return Content("This method will return all the customers"); } public ActionResult GetCustomers(string customerid) { return Content("This method will return individual customer"); }
Build the application after adding the above methods to the controller.
During the compile time, we will not get any errors, because C# supports polymorphism. The question is will this code will work in run time? if I run this application I will get the below error.
MVC is unsure which method to invoke. So let us try to figure out what is going on internally.
Polymorphism is an object-oriented concept that C# respects. MVC action methods are called using the HTTP protocol. A URL cannot contain a duplicate address or name.
The following question is, how do we implement polymorphism or run both methods?
We have an attribute in MVC called “ActionName”. The ActionName attribute is a type of action selector that is used to specify a different name for the action method. When we want that action method to be called with a different name rather than the method’s actual name, we use the ActionName attribute. and we can use this method to implement or run these methods.
[ActionName("Getall")] public ActionResult GetCustomers() { return Content("This method will return all customers"); } [ActionName("Getbyid")] public ActionResult GetCustomers(string customerid) { return Content("This method will return individual customer"); }
OUTPUT