Return View With ViewName in Controller Sample in MVC

Return View With ViewName in Controller Sample in MVC

Introduction

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...".

image.png

Step 2

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

Click on the "Add" button.

image.png

Step 3

Name the controller as in the following:

image.png

Step 4

Now we need to create a view.

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

image.png

Step 5

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.

image.png

Step 6

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

image.png

Step 7

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

image.png

Step 8

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.

image.png

Step 9

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

image.png

<< Day 4

>> Day 6