Menu Link in Layout Sample in MVC

Menu Link in Layout Sample in MVC

Introduction

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: Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.

image.png

Step 6: Add one more action method, AboutUs, in the "HomeController".

image.png

Step 7: Right-click on "AboutUs" and select "Add View...".

image.png

Step 8: Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.

image.png

So far we have created two views, Index and AboutUs. Now let's create a layout for these views.

Step 9: Right-click on "Views" and select "Add" >> "New Folder"

image.png

Step 10: Name the folder as "Shared", this will create a "Shared" folder under the view.

image.png

Step 11: Right-click on the "Shared" folder and select "Add" >> "View…".

image.png

Step 12: Name the view as "_Layout" and select "Empty (without model)" as the template.

image.png

Step 13: Design your desired layout in _Layout.cshtml.

Here we use the Html.ActionLink helper to set the link on the layout page. The first parameter is the link text, the second one is the action name and the third one is the controller name. Html.ActionLink does not link to a view but it creates a link to an action.

image.png

Step 14: Set the link for the index and aboutus as follows:

image.png

Step 15: Set "_Layout.cshtml" as the layout in both the views, in other words index and about us.

image.png

Step 16: Run the project, click on the "AboutUs" link and the "AboutUs" view is rendered.

image.png

[<< Day 7](dotnetbees.hashnode.dev/layout-for-all-view..

>> Day 9