Click here to Skip to main content
15,896,154 members
Articles / Web Development / ASP.NET
Tip/Trick

HandleUnknownAction in MVC

Rate me:
Please Sign up or sign in to vote.
4.73/5 (11 votes)
21 Oct 2014CPOL3 min read 25.5K   10   3
Advantages and uses of Controller.HandleUnknownAction in MVC Architecture

Introduction

MVC stands for Model-View-Controller. This is an architectural design for developing the application where the application is basically divided into 3 layers and each layer has its own relevant functionalities.

View provides the look and feel to the application what exactly the end user sees. These are the template files that your application uses to dynamically generate HTML responses and files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending on the language content.

Models are the classes like customer class, vendor class which contains the business logic, validation logic and data access logic. In MVC models, both hold and manipulate application data.

Controller is the heart of the application which controls the flow of application execution. It handles incoming browser requests, retrieves model data, and then specifies view templates that return a response to the browser.

Background

In MVC, browser request comes in the form of actions which are nothing but the function names in the controller class and the controller class can have many action methods defined within.

So when any browser requests an action along with the controller, the controller looks for an associated action name and returns the response in the form of views or files or might redirect to another controller action. So the question is now what if the controller doesn't find the associated action. And the answer will be it will throw the error.

Here I have added one controller class, i.e., EmpoyeeInfoController.cs. And it has the actions named GetEmployeeInfo, GetCompanyInfo and GetSalaryInfo. And I have defined the GetEmployeeInfo, GetCompanyInfo and not GetSalaryInfo.

C#
public ActionResult GetEmployeeInfo()
{
    return View();
}
public ActionResult GetCompanyInfo()
{
    return View();
}

So while calling the GetSalaryInfo. it is giving me the above error.

Image 1

In order to avoid this, we can use the "Controller.HandleUnknownAction". This method gets called when a controller cannot find an action method that matches a browser request. And in this action, we can customize our code by returning a view which will show the user a default message like "The action is an unknown action" or can log the Exception information or we can redirect to a different controller for further customized action. The defined functionality for this action can be like below:

ASP.NET
protected override void HandleUnknownAction(string actionName)
    {
        this.View(errorpage).ExecuteResult(this.ControllerContext);
    }

And now, it will give me the below output instead of that error.

Image 2

This is one way we can use the Controller.HandleUnknownAction. And there are other reasons we can use this function.

1. Method Overriding

Sometimes, we can find that there are so many actions that are not doing something besides calling the view with the same name like below:

C#
public ActionResult GetEmployeeInfo()
{
    return View();
}
public ActionResult GetCompanyInfo()
{
    return View();
}

So by overriding the method HandleUnknownAction() of the Controller class, we are able to merge them all to reduce the unnecessary lines of code and simplify the action calls.

C#
protected override void HandleUnknownAction(string actionName)
{
    this.View(actionName).ExecuteResult(this.ControllerContext);
}

2. Defining the Default Action

There might be a number of actions in the application which give the same result for the requested actions. In those cases, we can define one action with HandleUnknownAction and go ahead to give the output. We can also use switch case within this to define the various actions based on different conditions and a default action.

C#
protected override void HandleUnknownAction(string actionName)
{
    switch (actionName)
    {
        case "GetEmployee":
            this.RedirectToAction("GetEmployeeInfo").ExecuteResult(this.ControllerContext);
            break;
        case "GetCompany":
            this.RedirectToAction("GetCompanyInfo").ExecuteResult(this.ControllerContext);
            break;
        default:
            this.RedirectToAction("HomePage").ExecuteResult(this.ControllerContext);
            break;               
    }
}

Points of Interest

So with the above points, we can use the "HandleUnknownAction" more efficiently to resolve some of our problems with the below mentioned advantages of this function:

  • Exception handling for unknown action request
  • Method overriding
  • Defining the default action

History

  • 21st October, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
EsseyG27-Oct-14 2:46
professionalEsseyG27-Oct-14 2:46 
GeneralMy vote of 1 Pin
Member 1090330722-Oct-14 9:01
Member 1090330722-Oct-14 9:01 
SuggestionCovered many times before, I prefer a different solution... Pin
User 1013254621-Oct-14 13:30
User 1013254621-Oct-14 13:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.