(初识MVC Core)七、复用的View:View Component

时间:2022-12-21 11:28:58

1.优点:

1)相当于PartialView + 一个小型轻量级的Controller(注:PartialView无法包含业务逻辑)

2)适用于较为复杂业务

3)可以使用Razor语法

 

2.创建View Component

结构:

(初识MVC Core)七、复用的View:View Component

 

1)创建ViewComponents文件夹、MovieCountViewComponent.cs

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

namespace CoreModelTwo.ViewComponents
{
    public class MovieCountViewComponent : ViewComponent
    {
        private readonly IMovieService _movieService;

        //依赖注入
        public MovieCountViewComponent(IMovieService movieService)
        {
            _movieService = movieService;
        }


        public async Task<IViewComponentResult> InvokeAsync()
        {
            var movies = await _movieService.GetByCinemaAsync(1);
            var count = movies.Count();

            var movies2 = await _movieService.GetByCinemaAsync(1);
            count += movies2.Count();

            return View(count);
        }

    }
}

 

2)在Shared文件夹里创建文件夹Components、MovieCount和Default.cshtml

Default.cshtml:

@model int

<h2>Movie Count:</h2>
<h2>@Model</h2>

 

3)使用:在页面里头加入

@await Component.InvokeAsync("MovieCount")

 

(初识MVC Core)七、复用的View:View Component

 

结果显示:

(初识MVC Core)七、复用的View:View Component

 参阅:https://v.qq.com/x/page/x0750why9sm.html

 谢谢Dave

(初识MVC Core)七、复用的View:View Component