zoukankan      html  css  js  c++  java
  • .net core 使用ViewComponent

    .net core 中的局部视图组件是ViewComponent,可以用于建制重复使用公共功能组件

    一、新建一个类DemoViewComponent(必须以ViewComponent结尾)且继承ViewComponent

    using Microsoft.AspNetCore.Mvc;
    using NetCoreApiDemo.Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace NetCorePortal.Components
    {
        public class DemoViewComponent : ViewComponent
        {
            public async Task<IViewComponentResult> InvokeAsync()
            {
                List<tbl_page> pageList = new List<tbl_page>();
                for (int i = 0; i < 10; i++)
                {
                    pageList.Add(new tbl_page()
                    {
                        page_no = i.ToString(),
                        page_name = i.ToString()
                    });
                }
                return View(pageList);//此处没有返回ViewName 对应的视图文件是Default.cshtml
                //return View("D", pageList);//此处返回的ViewName 是“D” 对应的视图文件是D.cshtml
            }
        }
    }

    二、在View/Share目录下建立Components目录,并在此目录下建立Demo目录及对应Default.cshtml文件  

    @model IEnumerable<NetCoreApiDemo.Model.tbl_page>
    <h1>Demo IViewComponentResult</h1>
    <table>
        <tr>
            <th>page_no</th>
            <th>page_name</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.page_no</td>
                <td>@item.page_name</td>
            </tr>
        }
    </table>

     三、调用上面建立的 DemoViewComponent

    @{
        ViewData["Title"] = "Home Page";
    }
    
    @await Component.InvokeAsync("Demo")
  • 相关阅读:
    小米范工具系列之一:小米范 web查找器
    不同格式的ip 统一转成ip列表
    Educational Codeforces Round 32
    离散化方式
    线段树合并与分裂
    HDU1074
    容斥原理
    模板
    HDU1024 Max Sum Plus Plus
    CSA Round #56
  • 原文地址:https://www.cnblogs.com/zbspace/p/11620131.html
Copyright © 2011-2022 走看看