Create ASP.NET Core MVC 5 Project
On the Visual Studio, select Create a new project from Get Started
Select ASP.NET Core Web Application
Input Project Name and select Location for new project
Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish
Add Configurations
Open Startup.cs file and add new configurations as below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LearnASPNETCoreMVC5
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Demo}/{action=Index}/{id?}");
});
}
}
}
Create Controller
Create new folder named Controllers. In Controllers folder, create new controller as below:
Home Controller
Create new controller named HomeController.cs as below:
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVC5.Controllers
{
[Route("home")]
public class HomeController : Controller
{
[Route("")]
[Route("index")]
[Route("~/")]
public IActionResult Index()
{
return View();
}
}
}
Create View
In Views folder, create new views as below:
Home Views
In Views/Home folder, create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Home Page</h3>
<br />
<a asp-area="admin" asp-controller="home" asp-action="index">Link 1</a>
<br />
<a asp-area="admin" asp-controller="home" asp-action="index2" asp-route-id="123">Link 2</a>
</body>
</html>
Create Area
In project, create new area named Admin. In this area, create new Controller and Views as below:
Home Controller
In Area\Admin\Controllers folder, create new controller named HomeController.cs as below:
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVC5.Areas.Admin.Controllers
{
[Area("admin")]
[Route("admin/home")]
public class HomeController : Controller
{
[Route("")]
[Route("index")]
public IActionResult Index()
{
return View();
}
[Route("index2/{id}")]
public IActionResult Index2(int id)
{
Debug.WriteLine("id: " + id);
return View("Index");
}
}
}
Index View
In Views/Home folder, create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Home Admin Page</h3>
</body>
</html>
Structure of ASP.NET MVC Project
Run Application
Access Index action in Home controller with following url: http://localhost:49328
Output
Access Index action in Home controller in Admin area with following url: http://localhost:49328/admin/home/index
Output