Overloading MVC Action Methods

Introduction

 
In this blog, we are discussing how to overload the MVC action method. Let me explain this with a simple MVC application.
 
I have created an MVC application and added the customer controller. In this controller, I would like to implement polymorphism. In the same controller, I have added two action methods with the same name and different parameters.
 
Please check the below code snapshot.
  1. public ActionResult GetCustomers()  
  2.    {  
  3.       return Content("This method will return the all customers");  
  4.    }  
  5. public ActionResult GetCustomers(string customerid)  
  6.    {  
  7.       return Content("This method will return individual customer");  
  8.    }    
After adding the above methods in controller, build the application.  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.
 
Please check the below snapshot.
 
 
 
Now MVC is confused about which method to invoke. So let us try to understand what is happening internally. Now polymorphism is the object-oriented concept and it is respected by C#. In MVC action methods are invoked via HTTP protocol. In a URL we cannot have a duplicate address or name. The next question is how do we implement polymorphism or how do we run both methods? In MVC we have an attribute called action name, and using this method we can implement or run these methods. Please check the below code snippet. 
  1. [ActionName("Getall")]  
  2.  public ActionResult GetCustomers()  
  3.  {  
  4.     return Content("This method will return the all customers");  
  5.  }  
  6.  [ActionName("Getbyid")]  
  7.  public ActionResult GetCustomers(string customerid)  
  8.  {  
  9.      return Content("This method will return individual customer");  
  10.  }  
Please check the below sanpshot for the result.
 
 
 

Summary

 
In this blog we discussed the implementation of polymorphism in MVC action methods.