In this article we will see how to overload the action Method in ASP.NET MVC. Overloading is the scenario where we have two methods with
the same name but different signatures. At compile time, the compiler finds out which method it is going to call, based on the data
types of the arguments and the target of the method call. So the below piece of code where GetFileName is overloaded compiles without error.
namespace MvcOverloadExample.Controllers
{
public class HomeController : Controller
{
public ActionResult GetFileName()
{
return Content("Hi , this is a test file");
}
public ActionResult GetFileName(string EmpCode)
{
return Content("Hi , this is a test file created on Dec 8 , 2015");
}
}
However if we try to acccess GetFileName (http://localhost:61635/Home/GetFileName/), we will get the following error:
The current request for action 'GetFileName' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult GetFileName() on type WebApplication3.Controllers.HomeController
System.Web.Mvc.ActionResult GetFileName(System.String) on type MvcOverloadExample.Controllers.HomeController
If you want the overloading to work you need to apply "ActionName" as shown in the below code.
namespace MvcOverloadExample.Controllers
{
public class HomeController : Controller
{
public ActionResult GetFileName()
{
return Content("Hi , this is a test file");
}
[ActionName("GetFileWithCreatedDate")]
public ActionResult GetFileName(string EmpCode)
{
return Content("Hi , this is a test file created on Dec 8 , 2015");
}
}
After making the above change overloading will work. Test the controller GetFileName action method using the URL like this:
http://localhost:61635/Home/GetFileName(it will return message content: "Hi , this is a test file") . Now test the
controller GetFileWithCreatedDate action method using the URL like this:http://localhost:61635/Home/GetFileWithCreatedDate(it
will return message content: "Hi , this is a test file created on Dec 8 , 2015")
0 Comment(s)