In this quick post you will learn how a view can be rendered without its native Controller
Action method.
Action method.
Why we need this?
Let’s look at the image.
In above image, you can see for each view we have 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 a needless work. Even imagine
what you will do when you have hundreds or thousands of views. Will you create
hundreds or thousands of controller actions? Off course not, then how can we fix it?
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 a needless work. Even imagine
what you will do when you have hundreds or thousands of views. Will you create
hundreds or thousands of controller actions? Off course not, then how can we fix it?
In MVC Framework, controller class includes a method HandleUnknownAction() that
executes whenever we attempt to invoke an action (or when we request a view which
has no matching action method) on a controller that does not exist.
executes whenever we attempt to invoke an action (or when we request a view which
has no matching action method) on a controller that does not exist.
Now we are taking the advantage of the HandleUnknownAction() method to render views
even when a corresponding controller method does not exist.
even when a corresponding controller method does not exist.
In above image you can see we don’t have Post5.cshtml, so when I tried to access the
Post5.cshtml view, it pops following error.
Post5.cshtml view, it pops following error.
Exception Generated |
To fix this issue, we can use simple try-catch block and redirect the user on
PageNotFound view, here’s how.
I Hope this will Help you to Learn.