Create an area in MVC Core

An Area in ASP.NET Core MVC is a way to organize related functionality into separate sections of the application. This structure helps manage larger applications by grouping controllers, views, and models related to a specific feature or module, such as Admin, Owner, or Depo.

Here’s a step-by-step guide to creating and setting up an area in an ASP.NET Core MVC project, with a corrected and complete structure for an example area like "Owner" & “Customer”:

Step 1: Create an ASP.NET Core MVC Project

  1. Open Visual Studio.

  2. Create a new ASP.NET Core Web Application project.

  3. Choose the MVC template.

  4. Name your project and click Create.


Step 2: Create the Areas Folder

  1. In the Solution Explorer, right-click on the project root.

  2. Select Add > New Folder and name it Areas.


Step 3: Add an Area Folder

  1. Right-click the Areas folder.

  2. Add a new folder named Owner & Customer (or your desired area name).


Step 4: Create the Required Folders in the Owner & Customer Area

Inside the Owner & Customer folder, create the following folders:

  • Controllers

  • Views

The folder structure will look like this:

/Areas
   /Owner
      /Controllers
      /Views
   /Customer
      /Controllers
      /Views

Step 5: Add a Controller in the Owner Area

  1. Right-click the Controllers folder inside the Owner folder.

  2. Select Add > Controller > MVC Controller - Empty.

  3. Name the controller HomeController.


Step 6: Add [Area] Attribute to the Controller

Update the HomeController as follows:

using Microsoft.AspNetCore.Mvc;

namespace CRM.Areas.Owner.Controllers
{
    [Area("Owner")] // Specifies that this controller belongs to the "Owner" area
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Step 7: Create a View of the Index Action

  1. Right-click the Views folder in the Owner area.

  2. Create a folder named Home (it must match the controller name).

  3. Inside the Home folder, add a new Razor View named Index.cshtml.

Example Index.cshtml:

<h1>Welcome to the Owner Area</h1>

Step 8: Configure Routing for Areas

Update your Program.cs to include the area route. Place the area route before the default route:

app.MapControllerRoute(
    name: "areas",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

Step 9: Test the Area

  1. Build and run your application.

  2. Navigate to /Owner/Home/Index your browser.


Final Folder Structure

markdownCopy code/Areas
   /Owner
      /Controllers
         HomeController.cs
      /Views
         /Home
            Index.cshtml
/Controllers
/Views
wwwroot
Program.cs

Now your Owner area is fully set up and functional!