Introduction
In ASP.NET's Model-View-Controller (MVC) pattern, a view manages an app's representation of data and the user interaction. A view is just an HTML template that has an embedded Razor markup. A Razor markup is a code that interacts with an HTML markup to create a webpage that's sent to the client side.
In ASP.NET Core MVC, views are .cshtml files that use the C# language in a Razor markup. View files are grouped into folders according to the app's controllers. The folders are stored in a Views folder in the leading directory of the app.
In simple terms, an ASP.NET MVC application does not contain a display page when a URL request is made. The closest thing that can be considered a page is a View.
Creating a Controller in an ASP.NET MVC Application
In an ASP.NET MVC application, all browser requests are handled by a controller, and these requests are charted to controller actions. A controller action may return a view or perform other activity, such as redirecting to another controller action.
Hence we must know how a controller is created in ASP.NET MVC.
Let us start by creating our very own ASP.NET MVC Application.
Open Visual Studio and click on Create a new project.
Search for the ASP.NET Core Web App(Model-View-Controller) template and click next
Type the name of the project. In this example, the project name is MVCViewProject.
Set the Framework to.NET and the authentication type to none
We have successfully created our ASP.NET MVC application with all these steps completed.
To create a controller, we right-click on the Controllers located inside the Solution Explorer and hover over the Add option to click on the Controller option.
To keep things simple, let us create an empty MVC controller.
Now we are asked to name our controller. In this example, let us call the controller HomeController.
Now a HomeController.cs file will be created inside the Controllers folder.
Below is a sample code that will make our home controller functional.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCViewDemo.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public string Firstcontroller()
{
return "Congratulations, You created your first controller!";
}
}
}
Now, we run the project after pasting this code inside the HomeController.cs file.
After running the application, we will be redirected to our default browser and get an interface like this.
All we have to do is append /home/FirstController in our URL.