asp.net core視圖組件(ViewComponent)簡單使用

1、組成:

一個視圖組件包括兩個部分,派生自ViewComponent的類及其返回結果。相似控制器。html

定義一個視圖組件,如控制器同樣,必須是公開,非嵌套,非抽象的類。通常,視圖組件名稱爲類名去掉」ViewComponent「後綴。也可經過ViewComponentAttribute.Name屬性進行明確指定。async

2、視圖組件方法:

在InvokeAsync/Invoke方法中定義邏輯,並返回IViewComponentResult。參數可直接來源於視圖組件間調用,經過匿名類屬性進行傳遞。spa

3、視圖組件搜索路徑:

運行時對視圖搜索路徑以下:code

Views/Components/component

Views/Shared/Componentshtm

視圖組件默認名稱爲Default,經過可默認命名爲Default.cshtml;或可指定視圖名稱,在調用View方法返回時,將名稱一同返回。blog

4、視圖組件調用:

1.從視圖中調用

  @Component.Invoke("視圖組件名",<匿名類型參數>)。或@await Component.InvokeAsync("視圖組件名",<匿名類型參數>)ip

2.從控制器直接調用:

  直接在Action中返回,return ViewComponent("視圖組件名稱", new {arg0=xx,arg1=xxx});的形式調用。get

5、簡單示例:

經過建立一個視圖組件,返回前n個標識,進行顯示。string

視圖組件類:(則該視圖名稱爲」TopTags「)

namespace ViewComponentAbout.Components
{
    public class TopTagsViewComponent : ViewComponent
    {
        private readonly ITagService _tagService;

        public TopTagsViewComponent(ITagService tagService)
        {
            _tagService = tagService;
        }

        public IViewComponentResult Inovke(int count)
        {
            var tags = _tagService.LoadTopTags(count);
            var models = tags.Select((tag) =>
                new TagViewModel
                {
                    Id = tag.Id,
                    Name = tag.Name
                });
            return View(models);
        }

        public async Task<IViewComponentResult> InvokeAsync(int count)
        {
            var tags = await _tagService.LoadTopTagsAsync(count);
            var models = tags.Select((tag) =>
                new TagViewModel
                {
                    Id = tag.Id,
                    Name = tag.Name
                });
            return View(models);
        }
    }
}

數據來源Services:

namespace ViewComponentAbout.Services
{
    public interface ITagService
    {
        IEnumerable<Tag> LoadTopTags(int count);
        Task<IEnumerable<Tag>> LoadTopTagsAsync(int count);
    }
}

namespace ViewComponentAbout.Services
{
    public class TagService : ITagService
    {
        private static Func<List<Tag>> _tags = () =>
        {
            var tags = new List<Tag>();
            for (int i = 0; i < 100; ++i)
            {
                tags.Add(new Tag { Id = $"No.{i}", Name = $"Tag{i}", Description = "Tag entity", CreatedOn = DateTime.Now });
            }
            return tags;
        };

        public IEnumerable<Tag> LoadTopTags(int count)
        {
            return _tags().Take(count);
        }

        public async Task<IEnumerable<Tag>> LoadTopTagsAsync(int count)
        {
            return await Task.Run(() => _tags().Take(count));
        }
    }
}

 

實體:

namespace ViewComponentAbout.Entities
{
    public class Tag
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public DateTime CreatedOn { get; set; }
        public string Description { get; set; }
    }
}

ViewModel:

namespace ViewComponentAbout.ViewModels
{
    public class TagViewModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

視圖組件頁面:(位於/Views/Shared/Components/TopTags/Default.cshtml

@model IEnumerable<ViewComponentAbout.ViewModels.TagViewModel>

<style>
    ul li {color:purple;font-style:italic;}
</style>

@if(Model.Any())
{
    <ul>
        @foreach(var tag in Model)
        {
            <li>
                [@tag.Id] @tag.Name
            </li>
        }
    </ul>
}

Startup中,在ConfigureServices添加服務注入:

services.AddSingleton<ITagService, TagService>();

在Index.cshtml頁面中,使用以下:

@await Component.InvokeAsync("TopTags", new { count = 10 })

效果:


 

建立一個命名視圖組件:

獲取前10個Tag數據,如:(視圖名:Top10Tags

namespace ViewComponentAbout.Components
{
    public class Top10TagsViewComponent : ViewComponent
    {
        private readonly ITagService _tagService;

        public Top10TagsViewComponent(ITagService tagService)
        {
            _tagService = tagService;
        }

        public IViewComponentResult Inovke()
        {
            var tags = _tagService.LoadTopTags(10);
            var models = tags.Select((tag) =>
                new TagViewModel
                {
                    Id = tag.Id,
                    Name = tag.Name
                });
            return View("TagComponentName", models);
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var tags = await _tagService.LoadTopTagsAsync(10);
            var models = tags.Select((tag) =>
                new TagViewModel
                {
                    Id = tag.Id,
                    Name = tag.Name
                });
            return View("TagComponentName", models);
        }
    }
}

組件視圖頁面:(位於 /Views/Shared/Components/Top10Tags/TagComponentName.cshtml

@model IEnumerable<ViewComponentAbout.ViewModels.TagViewModel>

<style>
    ul li {color:purple;font-style:italic;}
</style>
There is only 10 tags in the component.
@if(Model.Any())
{
    <ul>
        @foreach(var tag in Model)
        {
            <li>
                [@tag.Id] @tag.Name
            </li>
        }
    </ul>
}

調用:

@await Component.InvokeAsync("Top10Tags")

效果:

相關文章
相關標籤/搜索