Return View With ViewName in Controller Sample in MVC - Day 5


This article describes returning a viewname from a controller.

Step 1. Create a MVC Project from the "Empty" Template

Right-click on "Controllers" and select "Add" >> "Controller...".


Step 2. Select "MVC 5 Controller - Empty"

Select "MVC 5 Controller - Empty" to add an empty controller.

Click on the "Add" button.

MVC controller

Step 3. Name the Controller

Name the controller as in the following:

Add controller

Step 4. Create a View

Now we need to create a view.

Right-click on "Index" and select "Add View...".

Home controller

Step 5. Change the View Name

Change the view name from "Index" to your desired name. By default it considers an action method name as the view name.

Select "Empty (without model)" as the template.

Click on the "Add" button.


Step 6. View Addition

This will add a view with the name "MyView".

View addition

Step 7. Run the Project

Now run the project and you will get the following error, because it tries to find the Index view and it is not there.

Run project

Step 8. Recover from the Error

So to recover from this error, we need to return the view with the viewname that we defined at the time of creation.

In this demo we have given a name "MyView", so we need to pass this name in the view method.

Recover from the error

Step 9. Run the Project Again

Run the project and you can see the controller returns the "MyView" view and it is rendered in the browser.

Local host

Similar Articles