标签:nbsp 依赖注入 业务逻辑 image htm return 显示 turn har
1.优点:
1)相当于PartialView + 一个小型轻量级的Controller(注:PartialView无法包含业务逻辑)
2)适用于较为复杂业务
3)可以使用Razor语法
2.创建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")
结果显示:
参阅:https://v.qq.com/x/page/x0750why9sm.html
谢谢Dave
(初识MVC Core)七、复用的View:View Component
标签:nbsp 依赖注入 业务逻辑 image htm return 显示 turn har
原文地址:https://www.cnblogs.com/dzw159/p/10591514.html