Home/MVC/Handling Unknown Actions in ASP.NET MVC

Handling Unknown Actions in ASP.NET MVC

Introduction:

In MVC, the request will be in the form of controller and action ( it is the name of controller and with action methods). So when browser request came, route will find the matched controller and action to response the browser with output. Here we are going to discuss about how to render view even when corresponding action does not exit. We will aware it will throw an error if matched action is not found inside the controller.

When to use MVCHandleUnknownAction ?

In below image, we can see each controller action has it’s own view in the application. One thing we can identify that Article1,Article2,Article3 has same piece of code. So here we having unnecessary redundant code in our application.

READ  Creating reusable method using @helper in MVC Razor

dotnet-helpers-HandleUnknownAction

To over come this problem, in MVC we are using MVCHandleUnknownAction method to handle the absence of action method inside the controller.

With absence of Action in controller:

Example :

In above image,we can see each controller action has it’s own view in the application. If we remove the action from the controller then it will thrown an error while requesting the same action as like below image.

READ  Server Side Model Validation in MVC 4 Razor

dotnet-helpers-HandleUnknownAction-Error

Handling Unknown Actions in ASP.NET MVC :

To render view even when corresponding action does not exit ( and alos to avoid redundant code), here we implementing the MVC HandleUnknownAction method instead of redundant Action (Article1,Article2,Article3)  in controller like Below Code.

public class HandleUnknownActionController : Controller
{
// GET: HandleUnknownAction
public ActionResult Index()
{
return View();
}
protected override void HandleUnknownAction(string actionName)
{
try
{
this.View(actionName).ExecuteResult(this.ControllerContext);
}
catch(Exception ex){// here we can catch the view not found error}
}
}

READ  Server-Side Comment in MVC

While browser request the articl1 action (eg: http://localhost:8080/HandleUnknownAction/article1), it  tried to access the article1 action inside the  controller. But there is no presence of Article1 action, so it has been caught by HandleUnKnownAction method as show below.

handlen-nonaction in mvc-dotnet-helpers

From the above code, HandleUnKnownAction method catch the incoming request and redirect the particular view if it present in the application. If its unable to find the view in-side our solution then it will be handle by the catch block.

OUTPUT :

dotnet-helpers-HandleUnknownAction-output

 

Keep Cool Coding…….

One Comment

  1. veni March 11, 2016 at 11:39 am

    good

Leave A Comment