ASP.NET 8 组件封装

本文介绍了如何在ASP.NETMVC项目中创建和使用ConfigurationInfo文件夹以及ConnectionStrings类,展示了如何通过ViewComponent实现实时配置文件的显示,包括模型绑定和视图渲染的过程。
摘要由CSDN通过智能技术生成

准备工作:

新建ConfigurationInfo文件夹,在该文件夹下新建类ConnectionStrings.cs(见配置部分ASP.NET 8 配置文件-CSDN博客

步骤:

1、新建ComponentExt文件夹,在该文件夹下新建类ConfigurationViewComponent.cs(ViewComponent是固定写法,类似Controller)

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WebApplication1.Utility.ConfigurationInfo;

namespace WebApplication1.Utility.ComponentExt
{
    public class ConfigurationViewComponet : ViewComponent
    {
        private readonly IConfiguration configuration;
        private readonly ConnectionStrings connectionStrings;
        private readonly ConnectionStrings options;

        public ConfigurationViewComponet(IConfiguration configuration, 
            IOptionsMonitor<ConnectionStrings> optionsMonitor, IOptions<ConnectionStrings> options)
        {
            this.configuration = configuration;
            this.connectionStrings = optionsMonitor.CurrentValue;
            this.options = options.Value;
        }

        //同步和异步方法只能用一个
        //public IViewComponentResult Invoke()
        //{
        //    return View("~/Utility/ComponentExt/Views/ConfigurationView", options);
        //}
      
        public async Task<IViewComponentResult> InvokeAsync()
        {
            return await Task.FromResult(View("~/Utility/ComponentExt/Views/ConfigurationView.cshtml", options));
        }
    }
}

2、在ComponentExt文件夹下新建文件夹Views,在Views中添加视图ConfigurationView.cshtml

@using WebApplication1.Utility.ConfigurationInfo;
@model ConnectionStrings

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<h1>配置文件信息如下:</h1>
<h2>@Model.WriteConnection</h2>

@foreach(var item in @Model.ReadConnectionList)
{
    <h3>@item</h3>
}

3、使用,在视图文件中添加如下代码,调用名称中不用写ViewComponent

@await Component.InvokeAsync("Configuration");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值