ASP. NET 5 Series tutorials (III): Introduction to view components, asp. netcomponents
In ASP. net mvc 6, view components (VCs) functions are similar to virtual views, but they are more powerful. VCs combines the advantages of views and controllers. You can regard VCs as a Mini controller. It controls a function module in an application, for example:
- Dynamic navigation menu
- Tag Cloud
- Logon panel
- Shopping Cart
- Recent articles
- Blog sidebar
If you use VC to create a logon panel, you can call it in many scenarios, such:
- User not logged on
- The user has logged on. You need to log on from another account or manage another account.
- If the current logon role is administrator, render the Administrator Logon panel
You can obtain data for rendering based on your needs. Add the VC to the page where the view control is required.
VC consists of two parts: Class (generally inherited from ViewComponent) and Razor view that calls methods in VC class. Similar to the ASP. NET controller, VC can be used as a POCO, but more users prefer to use methods and attributes inherited from VewComponent.
VC can be created in the following ways:
- Inherit ViewComponent.
- A class that owns the [ViewComponent] attribute or the [ViewComponent] attribute.
- The created name is alreadyViewComponentClass with a suffix.
Same as controllers, VCs must be a public, non-nested, and non-abstract class.
Add view component class
1. Create a nameViewComponentsThe View component class can be included in any folder in the project.
2. InViewComponentsCreate a folderPriorityListViewComponent. csClass ..
3. Use the following code to replacePriorityListViewComponent. csOriginal file code:
using System.Linq;using Microsoft.AspNet.Mvc;using TodoList.Models;namespace TodoList.ViewComponents{ public class PriorityListViewComponent : ViewComponent { private readonly ApplicationDbContext db; public PriorityListViewComponent(ApplicationDbContext context) { db = context; } public IViewComponentResult Invoke(int maxPriority) { var items = db.TodoItems.Where(x => x.IsDone == false && x.Priority <= maxPriority); return View(items); } }}
Code comment:
· Because PriorityListViewComponentClass inherited fromViewComponent, The class will be referenced from the View through the string "PriorityList" at runtime. It will be elaborated in the subsequent sections.
· The [ViewComponent] attribute is used to set the alias for referencing VC. For example, to create a class named XYZ, we can set its alias for referencing through the following code:
[ViewComponent(Name = "PriorityList")]public class XYZ : ViewComponent
· Components use the constructor to make the data content take effect, similar to the Todo controller function.
· Call the public method in View to pass any number of parameters. In the asynchronous version, InvokeAsync is available. In subsequent sections, we will refer to the use of InvokeAsync and multiple parameters. In the previous code, the return value of the public method is the agent (ToDoItems), and the priority is not lower than maxPriority.
Add View Controls
1. InViews \ TodoCreate a folderComponentsFolder. Note that this folder must be named Components.
2. InViews \ Todo \ ComponentsCreate a folderPriorityListFolder. The folder name must be consistent with the view component class name. Or remove the suffix name of the class name (if ViewComponent is used as the suffix when creating the class ). If the ViewComponent attribute is used.
3.In Views \ Todo \ Components \ PriorityListCreate a folderDefault. cshtmlIn the Razor view, add the following tags:
@model IEnumerable<TodoList.Models.TodoItem>
The Razor view contains and displays TodoItems. If the VC call method does not pass the view name (as shown in the example), the view name is called for the method by default. In subsequent articles, we will explain how to pass the view name.
InViews \ todo \ index. cshtmlAdd a div at the bottom of the view that calls PriorityListViewComponent:
@model IEnumerable<TodoList.Models.TodoItem>
@ Await Component. InvokeAsync () indicates that the syntax is used to call VC. The first parameter is the name of the component to be called. Other parameter parameters are passed to the VC. In this example, we pass "1" as the filtering priority. The InvokeAsync method can contain any number of parameters.
The priority list is displayed as a slice:
@{ ViewBag.Title = "ToDo Page";}<div class="jumbotron">
Note: VC is usually addedViews \ SharedFolder, because it is not just a controller.
Add InvokeAsync to priority component
Use the following code to update the PriorityListViewComponent class:
using System.Linq;using Microsoft.AspNet.Mvc;using TodoList.Models;using System.Threading.Tasks;namespace TodoList.ViewComponents{ public class PriorityListViewComponent : ViewComponent { private readonly ApplicationDbContext db; public PriorityListViewComponent(ApplicationDbContext context) { db = context; } // Synchronous Invoke removed. public async Task<IViewComponentResult> InvokeAsync(int maxPriority, bool isDone) { string MyView = "Default"; // If asking for all completed tasks, render with the "PVC" view. if (maxPriority > 3 && isDone == true) { MyView = "PVC"; } var items = await GetItemsAsync(maxPriority, isDone); return View(MyView, items); } private Task<IQueryable<TodoItem>> GetItemsAsync(int maxPriority, bool isDone) { return Task.FromResult(GetItems(maxPriority, isDone)); } private IQueryable<TodoItem> GetItems(int maxPriority, bool isDone) { var items = db.TodoItems.Where(x => x.IsDone == isDone && x.Priority <= maxPriority); string msg = "Priority <= " + maxPriority.ToString() + " && isDone == " + isDone.ToString(); ViewBag.PriorityMessage = msg; return items; } }}
Note:: The Invoke Method Used for synchronization is removed here and replaced by the more powerful asynchronous Method.
Modify the priority information displayed in the VC View:
@model IEnumerable<TodoList.Models.TodoItem>
Last, updateViews \ todo \ index. cshtmlView File:
@* Markup removed for brevity. *@ <div class="col-md-4"> @await Component.InvokeAsync("PriorityList", 2, true) </div></div>
The modification effects of the PriorityListViewComponent class and the Index view are displayed in slices:
View name
Some Complex VC may need to specify a specific view in some cases. The following Code specifies the view method through the InvokeAsync method:
public async Task<IViewComponentResult> InvokeAsync(int maxPriority, bool isDone){ string MyView = "Default"; // If asking for all completed tasks, render with the "PVC" view. if (maxPriority > 3 && isDone == true) { MyView = "PVC"; } var items = await GetItemsAsync(maxPriority, isDone); return View(MyView, items);}
ChangeViews \ Todo \ Components \ PriorityList \ Default. cshtmlIsViews \ Todo \ Components \ PriorityList \ PVC. cshtmlView. Change the PVC view control to verify its usage:
@model IEnumerable<TodoList.Models.TodoItem>
Finally, updateViews \ Todo \ Index. cshtmlFile:
Refresh the page to view the changes.
In MVC6, when changing the controller (or any other code), you do not need to re-compile or re-run the application. You only need to save the code and refresh the page.
The above is the view components knowledge we hope to share with you today. The next article will introduce the following two parts:
- Add to viewService method.
- Publish an applicationPublic cloudMethod.
Coming soon.
Link: http://www.asp.net/vnext/overview/aspnet-vnext/vc