Step 1
Create project
- Open Visual Studio 2015-> click File -> New-> Project.
- Visual C#-> Web -> ASP.NET Web Application-> write Project Name-> OK.
- Select MVC template. Empty-> Click MVC Folder-> OK.
- MVC Folders are created.
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.
- First user enters a URL in the Browser (www.google.com)
- It goes to the Server and calls an appropriate controller.
- The Controller uses the appropriate View and Model, creates the response and sends it back to the user.
- Controller handles the user's requests, so first we have to create a Controller
Step 2
Add Controller
- Go to the controllers folder-> Add-> Controller-> Select MVC 5 Controller Empty->Add.
- It will open Add Controller dialog, as shown below.
- Write Controller Name. Do not delete the word Controller. Remember, controller name must end with Controller.
- This will create HomeController class with Index method in HomeController.cs file under Controllers folder, as shown below.
Step 3
Add View
- Open a HomeController class -> right click inside Index method -> click Add View.
- In Add View dialogue box, keep the view name as Index.
- This will create View.
Step 4
- Write code in controller class as shown below
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace HelloWorldExample.Controllers {
- public class HomeController: Controller {
- public ActionResult Index() {
- ViewBag.message = "Hello World";
- return View();
- }
- }
- }
Step 5
- Write code in View as shown below
- @ {
- Layout = null;
- } < !DOCTYPE html > < html > < head > < meta name = "viewport"
- 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