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

This article describes returning a viewname from a controller.

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

Step 2

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

Click on the "Add" button.



Step 3

Name the controller as in the following:



Step 4

Now we need to create a view.

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



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.



Step 6

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



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.



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.



Step 9

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


<< Day 4                                   >> Day 6