Creating Controller and View in ASP.NET MVC

Hi Folks,

 

In our previous blog we discussed how to create a master page in ASP.NET MVC. Please checkout that blog before starting this because we are following the same project we created in that blog.

https://webdevelopmentknowledge.blogspot.com/2020/10/master-page-in-aspnet-mvc.html


1


 

Prerequisites: Basic knowledge of MVC and C# is useful if beginners also fine. we are using visual studio 2017 for this blog.


Here we will see how to create controller and create a view and an action method in ASP.NET MVC.

We have created an Web application. The project structure is as below.

2

Create a Controller:

               Lets go and Add new Controller for the project. To do that go to Controllers folder and Add new Controller as shown below.
3

after you will see below screen with many options. we will discuss about all in later blogs for now select MVC5 Controller - Empty and Click Add.
4

5


we are naming controller name as Login. Always controller names will be ending with Controller in ASP.NET MVC it is the naming convention by visual studio.

now we have successfully created a controller on our own.

6

 

Create a View:

  All the Methods inside Controller is called as Action Methods. By default one Index action method will be their in Login Controller. Now Right Click inside the Index action method and Add View.

 

6



7
In this window we have option to select Layout page . By default it will use "Views/Shared/_Layout.cshtml"
 
if you want to select layout page click on button beside use a layout page. After selection Click Add button to add a View.
8

View will be created under Views Folder -> Login Folder -> Index.cshtml

9

update Index.cshtml with below code.

Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Home -> Index</h2>


Run the project and navigate to Login/Index by the URL to see your View.

http://localhost:54085/Login/Index

in this URL Login represents Controller name and Index represents Action Method name in Controller.

Alt1

 In MVC requests are send based on URL we have Routing Concept in MVC. we will discuss about routing in our next blog.

I suggest using trello for project management and task tracking and organizing



Thanks for reading. Feel free to contact if any doubts share to your friends do follow for encouraging us.

Popular posts:



Post a Comment

1 Comments