Home > DeveloperSection > Forums > How to action overloading in MVC
Ankit Singh

Total Post:341

Points:2389
Posted on    October-27-2015 10:40 PM

 .NET Mvc 
Ratings:


 1 Reply(s)
 444  View(s)
Rate this:
Can anyone please help me how to solve this problem.


aditya kumar Patel

Total Post:250

Points:1782
Posted on    October-27-2015 10:46 PM



Overloading or in other words polymorphism is a feature of object oriented programming. So if you have some kind of a below controller code which has methods overloaded with same name and different argument's it would compile very well.

public class CustomerController : Controller

    {

       

        // GET: /Customer/

    Public ActionResult GetCustomer()

        {

         return Content("GetCustomer");

        }

    Public ActionResult GetCustomer(string id)

        {

         return Content("GetCustomer with a string");

        }

    } 

But now if you are thinking that when you call "http://localhost:3450/Customer/GetCustomer/" it should invoke "GetCustomer" and when you call "http://localhost:3450/Customer/GetCustomer/test" it should invoke "GetCustomer(string str)" you are WRONG.



Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism it works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

And i know if you answer with the above argument MVC interviewer would still press that he wants to implement polymorphism , so how do we go about doing it.

If you wish to keep polymorphism and also want the HTTP request to work you can decorate one of the methods with "ActionName" as shown in the below code.

public class CustomerController : Controller

    {

      

        // GET: /Customer/

    Public ActionResult GetCustomer()

        {

         return Content("GetCustomer");

        }

 

  [ActionName("GetCustomerbyid")]

    Public ActionResult GetCustomer(string id)

        {

         return Content("GetCustomer with a string");

        }

    }

So now you can invoke with URL structure "Customer/GetCustomer" the "GetCustomer" action and with URL structure "Customer/GetCustomerByName" the "GetCustomer(string id)" will be invoked.


Don't want to miss updates? Please click the below button!

Follow MindStick