ASP.NET Core Areas表示一个应用程序的功能模块,例如:administration,billing,sales等,如果应用程序非常大,有非常多的控制器、模型类、视图,这时我们可以创建多个Areas并将应用程序文件放到不同Areas下,这将更好帮助我们管理应用程序。Areas有他们自己的MVC目录结构,他们有自己的Controllers、Model、Views文件夹。
app.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}");area部分匹配url指定areas目标控制器,exists说明路由必须匹配这个约束,这个area路由匹配使用了[Area("Area name")]的所有控制器
namespace AspNetCore.Areas.Areas.Sales.Models { public class Product { public string Name { get; set; } public int Quantity { get; set; } public int Price { get; set; } } }接下来创建一个新的controller在Areas->Sales->Controllers文件夹下, 命名为HomeController.cs,添加下面代码:
using AspNetCore.Areas.Areas.Sales.Models; using Microsoft.AspNetCore.Mvc; namespace AspNetCore.Areas.Areas.Sales.Controllers { [Area("Sales")] public class HomeController : Controller { // 堆代码 duidaima.com public IActionResult Index() { Product[] productArray = new Product[] { new Product { Name = "Pants", Quantity = 5, Price=100 }, new Product { Name = "Shirts", Quantity = 10, Price=80 }, new Product { Name = "Shoes", Quantity = 15, Price=50 } }; return View(productArray); } } }注意:[Area("Sales")]特性使用在控制器上,使用他来关联Sales Area和控制器。
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers最后一部分在Areas->Sales->Views->Home文件夹下添加Index视图,内容如下:
@using AspNetCore.Areas.Areas.Sales.Models @model Product[] @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Routing</title> </head> <body> <table> <tr> <th>Name</th> <th>Quantity</th> <th>Price</th> </tr> @foreach (Product p in Model) { <tr> <td>@p.Name</td> <td>@p.Quantity</td> <td>@p.Price</td> </tr> } </table> </body> </html>这个视图将在HTML表格中显示所有产品,运行应用程序,我们将看到Sales Area的HomeController的Action方法被调用并且产品显示在浏览器上
<a asp-action="List">Link1</a>将会生成如下链接:
<a href="/Sales/Home/List">Link1</a>相同Area别的控制器下的action方法,我们能使用asp-controller="controller_name"帮助标签
<a asp-action="List" asp-controller="Report">Link</a>将会生成如下链接:
<a href="/Sales/Report/List">Link</a>五. asp-area 帮助标签
using Microsoft.AspNetCore.Mvc; namespace AspNetCore.Areas.Areas.Employee.Controllers { [Area("Employee")] public class HomeController : Controller { public IActionResult Index() { return View(); } } }修改Areas->Sales->Views->Home下的Index视图,创建一个链接使用asp-area帮助标签
<a asp-action="List" asp-controller="Home" asp-area="Employee">Link3</a>你将会发现生成如下链接:
<a href="/Employee/Home/List">Link3</a>六.从Area链接到应用程序主体目录
<a asp-action="List" asp-controller="Home" asp-area="">Link3</a>将生成下面链接:
<a href="/Home/List">Link4</a>总结