How to use Areas in ASP.NET Core?
Example Link : https://drive.google.com/file/d/1671rE4a499AQRI1tcoAIJLZQ1OWuKZHp/view?usp=sharing
Areas provide a way to partition an ASP.NET Core Web app into smaller functional groups, each with its own set of Razor Pages, controllers, views, and models. An area is effectively a structure inside an app.
For a large app, it may be advantageous to partition the app into separate high level areas of functionality. For instance, an e-commerce app with multiple business units, such as checkout, billing, and search. Each of these units have their own area to contain views, controllers, Razor Pages, and models.
How to Create Area in ASP.NET Core?
To create the area in ASP.NET core use following steps –
Step 1: Add the areas folder in your project.
Step 2: Right click on areas folder and select add, area option , it will add a folder with area name with controller, models & views folder.
How will be folder structure for area?
Consider an app that has two logical groups, Products and Services. Using areas, the folder structure would be similar to the following:
Project name
- Areas
- Products
- Controllers
- HomeController.cs
- ManageController.cs
- Views
- Home
- Index.cshtml
- Manage
- Index.cshtml
- About.cshtml
- Home
- Controllers
- Services
- Controllers
- HomeController.cs
- Views
- Home
- Index.cshtml
- Home
- Controllers
- Products
How to Configure Routing for Area?
To configure routing for area we have two step process –
- Use Area Attribute
- Define route for area.
Controllers with the [Area] attribute to associate the controller with the area:
[Area("Products")]
public class ManageController : Controller
{
The area route added to startup
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyArea",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
To invoke any action from the area we need to use the url –
/areaname/controllername/actionname
Layout for Areas
every area can have it’s own layout and _ViewStart File .