View without Controller Action in MVC

In this quick post you will learn how a view can be rendered without its native Controller 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?

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.


Now we are taking the advantage of the HandleUnknownAction() method to render views 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.


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


Hope this helps.

Comments

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples