分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

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

发布时间:2023-09-06 02:36责任编辑:苏小强关键词:MVC

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

原文地址:https://www.cnblogs.com/dzw159/p/10591514.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved