Handle View Without Controller Action in MVC

Why do we need this?

Let's look at the following image.

postcontroller

In the above image, you can see that for each view we have a matching controller action. Each of these actions contains a single line of code. In fact, each of these actions contains exactly the same line of code. And this is completely unnecessary. Imagine what you will do when you have hundreds or thousands of views. Will you create hundreds or thousands of controller actions? Of course not, then how can we fix it?

In the MVC Framework, the controller class includes a method, HandleUnknownAction(), that executes whenever we attempt to invoke an action (or when we request a view that has no matching action method) on a controller that does not exist.

no more

Now we are taking advantage of the HandleUnknownAction() method to render views even when a corresponding controller method does not exist.

In the image above you can see we don't have Post5.cshtml, so when I tried to access the Post5.cshtml view, it shows the following error.

view highlited

To fix this issue, we can use a simple try-catch block and redirect the user on a PageNotFound view; here's how.

multiple views

Ebook Download
View all
Learn
View all