Wednesday, 26 July 2017

ASP.NET MVC - Creating Hello World Application with Visual Studio 2017

What this article covers?

- Creating a Project in Visual Studio
- Adding Controller / How to Add Controller?
- Adding a View / How to generate a view from a Controller method?
- Adding a View / How to generate a view from a Controller method?
- Configuring Route / How to configure the default route? 

Creating a Project in Visual Studio

1.      Open Visual Studio

2.     On the File menu select New and then select New Project

3.     You’ll be prompted with the New Project window
4.     Select your programming language and then expand it to get all installed application types under it.
5.     Select Web option.
6.     Select ASP.NET Web Application Template and then enter the name of your application you wanted to create, then click OK.


7.     Click on Empty option to create the MVC application, and then check the MVC checkbox to create the empty MVC folder structure, and then click OK. Now your new ASP.NET MVC project is ready for you.



Adding Controller / How to Add Controller?

1.      Go to Solution Explorer
2.    Right Click on Controllers Folder
3.     Select Add, and then select Controller option

4.     Select an Empty MVC Controller Template and then click on Add.

5.     Enter your controller name (Controller name must end with the suffix Controller), and then click on Add.


6.     Now the controller class will be added to your project along with default Index action method as sown below.


7.     You can change the default controller action. I’m changing it from Index to HelloWorld.


Adding a View / How to generate a view from a Controller method?

1.      Right click on Index action method in controller, then select Add View option.

2.     The view name and controller name should be the same. So, don’t modify the default name. Uncheck ”Use a Layout Page” option, because we don’t have any layout page in our application, and then click on Add.
3.     Now the view will be added to your application. Add some welcome text as shown below.
4.


5.     Now your Controller and View are ready.


Configuring Route / How to configure the default route?  

Routing enable us to define URL pattern that maps to the request handler.
Every MVC application must configure (register) at least one route, which is configured by MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig.cs under App_Start folder. The following figure illustrates how to configure a Route in the RouteConfig class.

Modify the route parameters according to your Controller and View.
            

Now your view is configure as the default view for your application.
Run the application to see the output in browser.

No comments: