标签:Core ASP Razor Component NET View
前言
Razor Class Library 的用途是封装 Razor views, pages, controllers, page models, Razor components, View components, and data models, 到一个独立的 Library, 然后 share with multiple projects.
以前介绍 Identity – Introduction & Scaffold 的时候就有提到过, ASP.NET Core 封装了一些 Login, User Management 的 Pages, 方便我们快速启动 Identity.
官网的例子更多是用在 Blozor + Razor components. 但是我没有用 Blozor 和 Razor components. 我只用 Razor pages 和 View component.
所以这篇给的例子是 Razor Pages + View Component.
参考
Docs – Create reusable UI using the Razor class library project in ASP.NET Core
Docs – Consume ASP.NET Core Razor components from a Razor class library (RCL)
创建项目
1 个 web app, 一个 library.
mkdir TestRazorClassLibrary cd TestRazorClassLibrary dotnet new razorclasslib -o MyRazorLibrary --support-pages-and-views dotnet new webapp -o MyWebApp dotnet add MyWebApp reference MyRazorLibrary
注意: new razorclasslib 需要添加 --support-pages-and-views, 因为我要 share 的是 View Component.
最后一行是添加 reference, 因为 library 没有发布到 nuget.
创建 View Component in Library
用 VS Code 打开 TestRazorClassLibrary folder
把 build-in 创建的 Area 洗掉, 创建 component folder
HelloWorldViewComponent.cs
using Microsoft.AspNetCore.Mvc; namespace MyRazorLibrary; public class HelloWorldViewComponent : ViewComponent { public IViewComponentResult Invoke() { return View("~/Component/HelloWorld/Index.cshtml"); } }
Index.cshtml
<h1>Hello World</h1>
调用 View Component in Web App
Index.cshtml
@page @model IndexModel @addTagHelper *, MyRazorLibrary @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <vc:hello-world></vc:hello-world>View Code
运行
dotnet watch run --project MyWebApp
效果
标签:Core,ASP,Razor,Component,NET,View 来源: https://www.cnblogs.com/keatkeat/p/16291916.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。