ASP 5 Series Tutorial (iii): View Components Introduction

Source: Internet
Author: User
Tags actionlink

in ASP. NET MVC 6, the View Components (VCs) feature is similar to a virtual view, but more powerful. VCs takes into account the advantages of views and controllers, and you can think of VCs as a mini controller. It is responsible for controlling a functional module in the application, such as:

    • Dynamic navigation Menu
    • Tag Cloud
    • Login panel
    • Shopping Cart
    • Recent Articles
    • Blog side Sidebar

If you create a login panel using VC, you can call it in many scenarios, such as:

    • User not logged in
    • The user is logged in and needs to sign out using another account or manage another account.
    • Render Administrator Login Panel if the current login role is an administrator

You can get the data to render according to the user's needs. Add a VC to the page that needs the view control.

The VC contains two parts, a class (typically inherited from viewcomponent) and a razor view that calls methods in the VC class. Similar to the ASP. NET controller, VCs can be used as Poco, but more users tend to use methods and properties inherited from Vewcomponent.

VC is created in the following ways:

    • Inherit Viewcomponent.
    • Owns the [Viewcomponent] property, or a class derived from the owning [Viewcomponent] property.
    • Create a class that has the name viewcomponent as a suffix.

As with controllers, VCs must be public, non-nested, and non-abstract classes.

Add View Component Class

1. Create a folder named viewcomponents , and the View component class can be included under any folder in the project.

2. Create the PriorityListViewComponent.cs class under the viewcomponents folder.

3. Replace the original code of the PriorityListViewComponent.cs file with the following code:

usingSystem.Linq;usingMICROSOFT.ASPNET.MVC;usingTodolist.models;namespacetodolist.viewcomponents{ Public classprioritylistviewcomponent:viewcomponent {Private ReadOnlyApplicationdbcontext DB;  Publicprioritylistviewcomponent (Applicationdbcontext context) {db=context; }     PublicIviewcomponentresult Invoke (intmaxpriority) {      varItems = db. Todoitems.where (x = X.isdone = =false&&x.priority<=maxpriority); returnView (items); }  }}

Code Comment:

· Because the prioritylistViewcomponent class inherits from the viewcomponent, the runtime references the class from view through the string "Prioritylist". Detailed elaboration will be made in subsequent chapters.

· The [Viewcomponent] property is used to set the alias that references the VC, for example, to create a class with the name XYZ, and we can set its reference alias with the following code:

" prioritylist " )]publicclass xyz:viewcomponent

· The component uses a construction injector to make the data content effective, similar to the functionality of the Todo controller.

· Call the public method in view to pass any number of arguments. In the asynchronous version, InvokeAsync is available. In the subsequent chapters 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), with a priority of no less than maxpriority.

To add a view control

1. Create the Components folder under the views\todo folder, and note that this folder needs to be named components.

2. Create the prioritylist folder under the views\todo\components folder. The folder name must match the View component class name. Or the class name removes the suffix name (if you follow the convention when creating the class, use viewcomponent as the suffix). If the Viewcomponent property is used.

3. Create the default.cshtml Razor view under the views\todo\components\prioritylist folder and add the following markup:

@model ienumerable<todolist.models.todoitem>    @foreach (var in Model)    {        <li> @todo. Title</li>    }</ul>

The Razor view contains and displays the Todoitems. If the VC call method does not pass the name of the view (as shown in the example), then by default the view name is called for the method. In a subsequent article, you will explain how to pass the view name.

At the bottom of the views\todo\index.cshtml view, add a div with the call Prioritylistviewcomponent:

@model ienumerable<todolist.models.todoitem>    @foreach (var in Model)    {        <li> @todo. Title</li>    }</ul>

The tag @await Component.invokeasync () indicates that the syntax is used to invoke the VC. The first parameter is the name of the component we want to invoke. The remaining parameter parameters are passed to the VC. In this example, we pass "1" as the filter priority. The InvokeAsync method can contain any number of arguments.

The priority list is shown in slices:

@{Viewbag.title="ToDo Page";}<divclass="Jumbotron"> class="Row"> <divclass="col-md-4">@if (Model.count==0)    {          }    Else    {      <table> <tr><th>TODO</th><th></th></tr>@foreach (varTodoinchModel) {          <tr> <td> @todo. Title </td> <td>@Html. ActionLink ("Details","Details","Todo",New{id = Todo.} Id}) |@Html. ActionLink ("Edit","Edit","Todo",New{id = Todo.} Id}) |@Html. ActionLink ("Delete","Delete","Todo",New{id =Todo. ID})</td> </tr>        }      </table>              }    <div> @Html. ActionLink ("Create New Todo","Create","Todo") </div> </div> <divclass="col-md-4">@Component. Invoke ("prioritylist",1)     </div></div>

Note: VCs are usually added to the views\shared folder because it is not just a controller.

Adding InvokeAsync to Priority components

Update the Prioritylistviewcomponent class with the following code:

usingSystem.Linq;usingMICROSOFT.ASPNET.MVC;usingTodolist.models;usingSystem.Threading.Tasks;namespacetodolist.viewcomponents{ Public classprioritylistviewcomponent:viewcomponent {Private ReadOnlyApplicationdbcontext DB;  Publicprioritylistviewcomponent (Applicationdbcontext context) {db=context; }        //synchronous Invoke removed.                 Public AsyncTask<iviewcomponentresult> InvokeAsync (intMaxpriority,BOOLIsDone) {            stringMyView ="Default"; //If asking for all completed tasks, render with the "PVC" view.            if(Maxpriority >3&& IsDone = =true) {MyView="PVC"; }            varItems =awaitGetitemsasync (maxpriority, IsDone); returnView (MyView, items); }        PrivateTask<iqueryable<todoitem>> Getitemsasync (intMaxpriority,BOOLIsDone) {            returnTask.fromresult (GetItems (maxpriority, IsDone)); }        PrivateIqueryable<todoitem> GetItems (intMaxpriority,BOOLIsDone) {            varItems = db. Todoitems.where (x = X.isdone = = IsDone &&x.priority<=maxpriority); stringmsg ="Priority <="+ maxpriority.tostring () +"&& IsDone = ="+isdone.tostring (); Viewbag.prioritymessage=msg; returnitems; }    }}

Note : This removes the Invoke method for synchronization and replaces it with a more powerful asynchronous method.

To modify the VC view display priority information:

@model ienumerable<todolist.models.todoitem>    @foreach (var in Model)    {        <li> @todo. Title</li>    }</ul>

Finally, update the views\todo\index.cshtml view File:

 for brevity. *@        class="col-md-4">        @await component.invokeasync (  "prioritylist"2true)    </div> </div>

The Prioritylistviewcomponent class and the index view are displayed in slices to modify the effect:

Specify the view name

Some complex VCs may need to specify a particular view in some cases, the following code is the method of specifying the view through the InvokeAsync method:

 Public AsyncTask<iviewcomponentresult> InvokeAsync (intMaxpriority,BOOLIsDone) {    stringMyView ="Default"; //If asking for all completed tasks, render with the "PVC" view.    if(Maxpriority >3&& IsDone = =true) {MyView="PVC"; }    varItems =awaitGetitemsasync (maxpriority, IsDone); returnView (MyView, items);}

Change views\todo\components\prioritylist\default.cshtml to views\todo\components\prioritylist\ pvc.cshtml view. Change the PVC view control to verify its use:

@model ienumerable<todolist.models.todoitem>    @foreach (var in Model)    {         <li> @todo. Title</li>    }</ul>

Finally, the views\todo\index.cshtml file needs to be updated:

Refresh the page to see the effect of the change.

In MVC6, when you change the controller (or any other code), you do not need to recompile or rerun the app, just save the Code and refresh the page.

These are the view components that we would like to share with you today, and in the next article we will cover the following two parts:

    • Adds a service method to the view .
    • Publish the application to the public cloud method.

Please look forward to it.

Original link: HTTP://WWW.ASP.NET/VNEXT/OVERVIEW/ASPNET-VNEXT/VC

ASP. 5 Series Tutorial (iii): View Components Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.