0
点赞
收藏
分享

微信扫一扫

Asp.Net core 视图组件ViewComponent

先峰老师 2022-02-08 阅读 50

视图组件 ViewComponent

  • 最近用了一下视图组件,还挺方便的,如果遇到公共的部分,可以抽出来,写成视图组件,方便调用

先上图看一下效果:比如首页的4个画红框的地方是4个模块,有些地方可能要重复用到,那么我们用视图组件就很方便。
在这里插入图片描述

  • 开始编码步骤

第一步,先新建一个项目
在这里插入图片描述

第二步,添加视图组件类
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace demoViewComponents.Components
{
    public class OneViewComponent : ViewComponent
    {
        /*
         如果需要构造函数的话,你就创建
             */
        /// <summary>
        /// 构造函数
        /// </summary>
        public OneViewComponent()
        {

        }
        /// <summary>
        /// 异步调用
        /// </summary>
        /// <returns></returns>
        public async Task<IViewComponentResult> InvokeAsync()
        {

            return View();
        }

    }
}

这里说明一下,之前是可以加

public IViewComponentResult Invoke()
{
return View();
} 

这个方法,但是现在好像加不了,只能用异步方法,加了会报错,请测试

第三步,添加视图页面
在这里插入图片描述

namespace demoViewComponents.Components
{
    public class ThreeViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            return View("three");
        }
    }
}

第四步,页面加载视图组件

<div class="row">
    @await Component.InvokeAsync("One")    

    @await Component.InvokeAsync("Tow")

    @await Component.InvokeAsync("Three")

    @await Component.InvokeAsync("Four")

</div>

通过@await Component.InvokeAsync("Nmae") 的方式来绑定视图组件

举报

相关推荐

0 条评论