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.
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.
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}
}
}
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.
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 :
Keep Cool Coding…….
good