×

iFour Logo

Overloading Action Method in Asp.Net MVC

Kapil Panchal - June 03, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Overloading Action Method in Asp.Net MVC

What is Overloading?


In any Object-Oriented Programming Language, there is a concept called Method Overloading. It simply means to have two or more functions or methods with the same name but different parameters.

Here is a simple example of it.

 
static int Add(int x, int y)
{
return x + y;
}
static double Add(double x, double y)
{
return x + y;
}
static void Main(string[] args)
{
int num1 = Add(6, 9);
double num2 = Add(4.2, 69.69);
Console.WriteLine("Int: " + num1);
Console.WriteLine("Double: " + num2);
}

What is ASP.NET Filter?


In Asp.Net MVC, the User’s request is routed to the specific controller and action method. Although, there might be situations where one wants to apply logic before and after any action method execution. ASP.NET Filters are applied to use this purpose.

ASP.NET Filter is a custom class that is used to write custom logic for execution prior and/or after an action method is executed. It can be applied to any action or controller.

There are mainly four types of filters:

  1. Authorization Filter
  2. Action Filter
  3. Result Filter
  4. Exception Filter

Each type is executed at a different stage in the pipeline and thus has its own set of intended cases. Choose what kind of filter to create based on the task you need it to perform, and wherein request pipeline it executes.

What is Action Filter?


Action filter’s execution happens before and after an action method executes. Action filter attributes can be applied to a specific action and/or to a controller. When an action filter is applied to a controller, it is applied to all the action methods.

The OutputCache is a system action filter attribute that can be used to an action method for which we want to cache the output.

For example, the output of this action method will be cached for 50 seconds.

 
[OutputCache(Duration=50)]
public ActionResult Index()
{
return View();
}

Steps to create a custom Action Filter


1.Create a class

2.Inherit it from ActionFilterAttribute class

3.Override at least one of these methods:

 
  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

Example:

using System;
using System.Diagnostics;
using System.Web.Mvc;
namespace WebApplication1
{
public class MyFirstCustomFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.GreetMesssage = "Hello World";
base.OnResultExecuting(filterContext);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controllerName = filterContext.RouteData.Values["controller"];
var actionName = filterContext.RouteData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", "onexecuting", controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
base.OnActionExecuting(filterContext);
}
}

In this program, we are setting ViewBag property for the controllers being executed. The ViewBag property must be set before a controller action result is executed since we are overriding the OnResultExecuting method. Also, it is overriding OnActionExecuting to log the information about the controller’s action method.

If you want to increase the security of a certain section of your website, you can place an [Authorize] attribute on an ActionResult method in your controller. If someone visits your website and they try to hit that page and they aren't authorized, they are sent to the login page (Of course, you need to modify your web.config to point to the login page for this to work properly).

 
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var httpContext = context.HttpContext;
if (!httpContext.User.Identity.IsAuthenticated)
{
if (httpContext.Request.Url != null)
{
var redirectOnSuccess = httpContext.Request.Url.AbsolutePath;
var urlHelper = new UrlHelper(context.RequestContext);
var url = urlHelper.LoginUrl(redirectOnSuccess);
httpContext.Response.Redirect(url, true);
}
}
base.OnActionExecuting(context);
}
}

Possible levels of Action Filters

1. As Global Filter

A filter can be added to the global filter in App_Start\FilterConfig. After applying this, one can use this for all the controllers in the Application.

 
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyFirstCustomFilter());
}
}
2. At Controller Level

To apply the filter at the controller level, we should apply it as an attribute to a controller. At the time of applying to the controller level, action will be available to all controllers.

 
[MyFirstCustomFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
3. At Action Level
To apply the filter at the action level, we should apply it as an attribute of the action.

Method Overloading in MVC


When we try to implement the same concept in MVC, the compilation process will be executed successfully and we won't get any errors, because C# supports the concept of Polymorphism. But, when we try to run the application, we will get the error.

Here is the example:

 
public ActionResult GetCustomers()  
{  
return Content("This method will return all customers");  
}  
public ActionResult GetCustomers(string customerid)  
{  
return Content("This method will return individual customer");  
}

ai-Hiring-banner

Figure 1: Error at the run-time

In this situation, the MVC is confused about methods. It simply does not know which method should be invoked. Polymorphism is the Object-Oriented concept and it is used in C# as well. MVC action methods are strictly invoked via HTTP (Hypertext Transfer Protocol). In the URL, it should not be any duplicate value of address or name. To overcome this, we must use an attribute called action name, and by using this we can implement and run these methods.

Looking for Trusted Dot Net Development Company ? Your Search ends here.

Here is the improvised snipped of the same program:

[ActionName("Getall")]  
public ActionResult GetCustomers()  
{  
return Content("This method will return all customers");  
}  
[ActionName("Getbyid")]  
public ActionResult GetCustomers(string customerid)  
{  
return Content("This method will return individual customer");  
}

ai-Hiring-banner

Figure 2: Improvised Code Snippet

How to overload the Action Method in MVC?


As we discussed in the prior topics, the method overloading can not be implemented directly in the MVC. We must change the ActionName as shown below:

 
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  

namespace MvcApplication5.Controllers
{
public class HomeController : Controller  
{
public ActionResult GetEmpName()
{
return Content("This is the test Message");  
}
[ActionName("GetEmpWithCode")]
public ActionResult GetEmpName(string EmpCode)
{
return Content("This is the test Messagewith Overloaded");
}
}
}

Now, when we want to run the controller GetEmpName action method, open this URL in your browser:

http://localhost:49389/Home/GetEmpName

ai-Hiring-banner

Figure 3: Output

To run the controller GetEmpWithCode action method, open this URL:

http://localhost:49389/Home/GetEmpWithCode

ai-Hiring-banner

Figure 4: Output

Conclusion


In this blog, we learned what is Method Overloading, MVC Action Methods, How to create Action Methods. We have also discussed how to overload the Action Method using C# practically.

Overloading Action Method in Asp.Net MVC Table of Content 1. What is Overloading? 2. What is ASP.NET Filter? 3. What is Action Filter? 4. Steps to create a custom Action Filter 4.1. Possible levels of Action Filters 5. Method Overloading in MVC 6. How to overload the Action Method in MVC? 7. Conclusion   What is Overloading? In any Object-Oriented Programming Language, there is a concept called Method Overloading. It simply means to have two or more functions or methods with the same name but different parameters. Here is a simple example of it.   static int Add(int x, int y) { return x + y; } static double Add(double x, double y) { return x + y; } static void Main(string[] args) { int num1 = Add(6, 9); double num2 = Add(4.2, 69.69); Console.WriteLine("Int: " + num1); Console.WriteLine("Double: " + num2); } What is ASP.NET Filter? In Asp.Net MVC, the User’s request is routed to the specific controller and action method. Although, there might be situations where one wants to apply logic before and after any action method execution. ASP.NET Filters are applied to use this purpose. ASP.NET Filter is a custom class that is used to write custom logic for execution prior and/or after an action method is executed. It can be applied to any action or controller. There are mainly four types of filters: Authorization Filter Action Filter Result Filter Exception Filter Each type is executed at a different stage in the pipeline and thus has its own set of intended cases. Choose what kind of filter to create based on the task you need it to perform, and wherein request pipeline it executes. What is Action Filter? Action filter’s execution happens before and after an action method executes. Action filter attributes can be applied to a specific action and/or to a controller. When an action filter is applied to a controller, it is applied to all the action methods. The OutputCache is a system action filter attribute that can be used to an action method for which we want to cache the output. For example, the output of this action method will be cached for 50 seconds.   [OutputCache(Duration=50)] public ActionResult Index() { return View(); } Read More: .net Highcharts With Mvc Applications Steps to create a custom Action Filter 1.Create a class 2.Inherit it from ActionFilterAttribute class 3.Override at least one of these methods:   OnActionExecuting OnActionExecuted OnResultExecuting OnResultExecuted Example: using System; using System.Diagnostics; using System.Web.Mvc; namespace WebApplication1 { public class MyFirstCustomFilter : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.Controller.ViewBag.GreetMesssage = "Hello World"; base.OnResultExecuting(filterContext); } public override void OnActionExecuting(ActionExecutingContext filterContext) { var controllerName = filterContext.RouteData.Values["controller"]; var actionName = filterContext.RouteData.Values["action"]; var message = String.Format("{0} controller:{1} action:{2}", "onexecuting", controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); base.OnActionExecuting(filterContext); } } In this program, we are setting ViewBag property for the controllers being executed. The ViewBag property must be set before a controller action result is executed since we are overriding the OnResultExecuting method. Also, it is overriding OnActionExecuting to log the information about the controller’s action method. If you want to increase the security of a certain section of your website, you can place an [Authorize] attribute on an ActionResult method in your controller. If someone visits your website and they try to hit that page and they aren't authorized, they are sent to the login page (Of course, you need to modify your web.config to point to the login page for this to work properly).   public class RequiresAuthenticationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { var httpContext = context.HttpContext; if (!httpContext.User.Identity.IsAuthenticated) { if (httpContext.Request.Url != null) { var redirectOnSuccess = httpContext.Request.Url.AbsolutePath; var urlHelper = new UrlHelper(context.RequestContext); var url = urlHelper.LoginUrl(redirectOnSuccess); httpContext.Response.Redirect(url, true); } } base.OnActionExecuting(context); } } Possible levels of Action Filters 1. As Global Filter A filter can be added to the global filter in App_Start\FilterConfig. After applying this, one can use this for all the controllers in the Application.   public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new MyFirstCustomFilter()); } } 2. At Controller Level To apply the filter at the controller level, we should apply it as an attribute to a controller. At the time of applying to the controller level, action will be available to all controllers.   [MyFirstCustomFilter] public class HomeController : Controller { public ActionResult Index() { return View(); } } 3. At Action Level To apply the filter at the action level, we should apply it as an attribute of the action. Method Overloading in MVC When we try to implement the same concept in MVC, the compilation process will be executed successfully and we won't get any errors, because C# supports the concept of Polymorphism. But, when we try to run the application, we will get the error. Here is the example:   public ActionResult GetCustomers() { return Content("This method will return all customers"); } public ActionResult GetCustomers(string customerid) { return Content("This method will return individual customer"); } Figure 1: Error at the run-time In this situation, the MVC is confused about methods. It simply does not know which method should be invoked. Polymorphism is the Object-Oriented concept and it is used in C# as well. MVC action methods are strictly invoked via HTTP (Hypertext Transfer Protocol). In the URL, it should not be any duplicate value of address or name. To overcome this, we must use an attribute called action name, and by using this we can implement and run these methods. Looking for Trusted Dot Net Development Company ? Your Search ends here. See here Here is the improvised snipped of the same program: [ActionName("Getall")] public ActionResult GetCustomers() { return Content("This method will return all customers"); } [ActionName("Getbyid")] public ActionResult GetCustomers(string customerid) { return Content("This method will return individual customer"); } Figure 2: Improvised Code Snippet How to overload the Action Method in MVC? As we discussed in the prior topics, the method overloading can not be implemented directly in the MVC. We must change the ActionName as shown below:   using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication5.Controllers { public class HomeController : Controller { public ActionResult GetEmpName() { return Content("This is the test Message"); } [ActionName("GetEmpWithCode")] public ActionResult GetEmpName(string EmpCode) { return Content("This is the test Messagewith Overloaded"); } } } Now, when we want to run the controller GetEmpName action method, open this URL in your browser: http://localhost:49389/Home/GetEmpName Figure 3: Output To run the controller GetEmpWithCode action method, open this URL: http://localhost:49389/Home/GetEmpWithCode Figure 4: Output Conclusion In this blog, we learned what is Method Overloading, MVC Action Methods, How to create Action Methods. We have also discussed how to overload the Action Method using C# practically.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.