HOW TO ACTION OVERLOADING IN MVC

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
Mvc 
 765  View(s)
Ratings:
Rate this:
Can anyone please help me how to solve this problem.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to action overloading in MVC

    
    
    

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!