Tuesday, April 28, 2015

Can we have same action methods in MVC?

This question was asked during an interview. 

For moment I wondered why interviewer such kind of questions which does not test anything about programmer's ability. But let's leave that argument from some other day and lets answer this question.
Lets explore more on this with an example.


Same action method means, it will be a method overloading concept.


Overloading or in other words polymorphism is a feature of object oriented programming. 


So if we 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 LoadCustomer()
{
return Content("LoadCustomer");
}
public ActionResult LoadCustomer(string str)
{
return Content("LoadCustomer with a string");
}
}
 
 
But now if you are thinking that when you call 
"http://localhost:3450/Customer/LoadCustomer/" it should invoke
"LoadCustomer" and when you call
"http://localhost:3450/Customer/LoadCustomer/test" it should invoke
"LoadCustomer(string str)" you are WRONG.



If we try to do this, we will end with a below error. Read the word
"Ambiguous" in the error. Ok , let us see
more in detail what the below error means.

 


 
 
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 we know if we 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 we wish to keep polymorphism and also want the HTTP request to work
we can decorate one of the methods with "ActionName" as shown in the
below code.


public class CustomerController : Controller
{
//
// GET: /Customer/

public ActionResult LoadCustomer()
{
return Content("LoadCustomer");
}

[ActionName("LoadCustomerbyName")]
public ActionResult LoadCustomer(string str)
{
return Content("LoadCustomer with a string");
}
}
 
So now we can invoke with URL structure "Customer/LoadCustomer" the 
"LoadCustomer" action and with URL structure
"Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be
invoked.
 
 
 
 
 
 

No comments:

Post a Comment