Hello World Program In ASP.NET MVC

Step 1

Create project

  1. Open Visual Studio 2015-> click File -> New-> Project.

    Create project

  2. Visual C#-> Web -> ASP.NET Web Application-> write Project Name-> OK.

    Create project

  3. Select MVC template. Empty-> Click MVC Folder-> OK.

    Create project

  4. MVC Folders are created.

    Create project

Let's understand MVC architecture in ASP.NET

MVC stands for Model, View and Controller. MVC separates an application into three components - Model, View and Controller.

Model

Model represents the shape of the data and business logic. It maintains the data of the Application. Model objects retrieve and store model state in a database.

View

View is a user interface. View displays the data, using model, to the user and also enables them to modify the data.

Controller

Controller handles the user request.

The flow of the user's request in ASP.NET MVC is given below.

Create project

  1. First user enters a URL in the Browser (www.google.com)
  2. It goes to the Server and calls an appropriate controller.
  3. The Controller uses the appropriate View and Model, creates the response and sends it back to the user.
  4. Controller handles the user's requests, so first we have to create a Controller

Step 2

Add Controller

  1. Go to the controllers folder-> Add-> Controller-> Select MVC 5 Controller Empty->Add.

    Create project

    Create project

  2. It will open Add Controller dialog, as shown below.

    Create project

  3. Write Controller Name. Do not delete the word Controller. Remember, controller name must end with Controller.

    Create project


  4. This will create HomeController class with Index method in HomeController.cs file under Controllers folder, as shown below.

    Create project

Step 3

Add View

  1. Open a HomeController class -> right click inside Index method -> click Add View.

    Create project

  2. In Add View dialogue box, keep the view name as Index.

    Create project

  3. This will create View.

    Create project

Step 4

  1. Write code in controller class as shown below  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace HelloWorldExample.Controllers {  
  8.     public class HomeController: Controller {  
  9.         public ActionResult Index() {  
  10.             ViewBag.message = "Hello World";  
  11.             return View();  
  12.         }  
  13.     }  
  14. }  
Step 5
  1. Write code in View as shown below  
  2. @ {  
  3.     Layout = null;  
  4. } < !DOCTYPE html > < html > < head > < meta name = "viewport"  
  5. content = "width=device-width" / > < title > Index < /title> < /head> < body > < div > @ViewBag.message < /div> < /body> < /html>  
Note

Here, I am using ViewBag. It is used to transfer the data from the controller to the view.

Output

Create project
 
Ebook Download
View all
Learn
View all