gpt4 book ai didi

c# - 在我的 Controller 中使用来自其他类库的 View

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:15 25 4
gpt4 key购买 nike

假设我有一个名为 Controllers 的类库和另一个名为 Views 的类库

Views 中有我的 .cshtml 文件,在 Controllers 中有我的 .cs

我如何“说服”我的 Controller 使用来自名为 Views 的项目/类库中的 Views

项目结构:

|
|
|-- MyViews
|
|-- MyTestView.cshtml
|-- Shared
|
|-- shared.cshtml
|-- Controllers
|-- AppRunner (Program Main, Startup.cs)

我试过了

// {2} is area, {1} is controller,{0} is the action    

services.Configure<RazorViewEngineOptions>(o =>
{
o.ViewLocationFormats.Clear();
o.ViewLocationFormats.Add("/MyViews/{1}/{0}" + RazorViewEngine.ViewExtension);
o.ViewLocationFormats.Add("/MyViews/Shared/{0}" + RazorViewEngine.ViewExtension);
}

services.Configure<RazorViewEngineOptions>(o =>
{
o.ViewLocationFormats.Clear();
o.ViewLocationFormats.Add("~/MyViews/{1}/{0}" + RazorViewEngine.ViewExtension);
o.ViewLocationFormats.Add("~/MyViews/Shared/{0}" + RazorViewEngine.ViewExtension);
}

services.Configure<RazorViewEngineOptions>(o =>
{
o.ViewLocationFormats.Clear();
o.ViewLocationFormats.Add("/../MyViews/{1}/{0}" + RazorViewEngine.ViewExtension);
o.ViewLocationFormats.Add("/../MyViews/Shared/{0}" + RazorViewEngine.ViewExtension);
}

但它们都返回无法在这些位置找到 cshtml 文件的错误

最佳答案

主网络应用程序中的 View 将始终覆盖类库中的 View 。但是 View 肯定可以从与 Controller 不同的类库中使用。

为了发现您的 View 类库中的 View ,您的 View 类库必须使用 sdk Microsoft.NET.Sdk.Razor,并且它必须直接依赖于 Microsoft.AspNetCore.Mvc

否则它将看不到您的类库中的 View 。

并且主 Web 应用程序必须引用类库。

您不需要那个 View 位置扩展器逻辑。

更新:

您的 View 项目 csproj 应如下所示:

<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="path-to-yourview-models-project.csproj" />
--maybe other project refs here
</ItemGroup>
</Project>

请注意 Microsoft.NET.Sdk.Razor 不是包依赖项。

此外,您的类库中的 View 需要与主 Web 应用程序中相同的文件夹结构约定。

 Views
Home
.cshtml files
Shared
.cshtml files
_ViewImports.cshtml

可以放在 Controller 名称对应的不带“Controller”后缀的文件夹中,也可以全部放在shared中

关于c# - 在我的 Controller 中使用来自其他类库的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54554100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com