gpt4 book ai didi

c# - 如何在 .NET Core 的主布局 View 中呈现特定 Controller 的 Action ?

转载 作者:行者123 更新时间:2023-11-30 21:32:14 25 4
gpt4 key购买 nike

我正在从 Layout 主视图中调用部分 "TopNav"

我希望 TopNav View 是强类型的,并且要在 TopNavController 中创建模型。

有什么方法可以从主视图中呈现特定 Controller 的操作吗?所以在这种情况下,我需要在 Layout 中呈现 TopNavControllerTopNav 操作。

到目前为止我只能使用例如。 @Html.Partial("TopNav")@Html.RenderPartial("TopNav") 可以选择传递模型,但我需要在 Controller 中实例化模型。

在以前的版本中曾经有 Html.Action("Action", "Controller") 帮助程序,但在 .NET Core 中似乎不再可用。

最佳答案

对于 为什么 @Html.Action(..) 在此处的 GitHub 问题中被删除有一个很好的解释:Why was @Html.Action removed? .

We removed them because we came up with what we felt was an overall better feature called View Components.

鉴于该建议,很明显,您的示例的建议是创建一个 View Component ,按照惯例将命名为 TopNavViewComponent

ViewComponents/TopNavViewComponent.cs

public class TopNavViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
// Code to instantiate the model class.
var yourModelClass = ...

return View(yourModelClass);
}
}

View 的调用在已知位置查找 Default.cshtml Razor 文件。下面是该文件的示例(其预期位置以粗体显示):

Shared/Components/TopNav/Default.cshtml

@model YourModelClassType

@*
Your HTML, etc.
Standard Razor syntax and HTML can be used here.
*@

要使用这个新的 View 组件,请将以下内容添加到您的 Layout View 中,无论您希望在何处呈现输出:

Shared/_Layout.cshtml

@await Component.InvokeAsync("TopNav")

这应该足以让您开始使用 View 组件。其他一些有用的知识是:

  1. View Components 支持依赖注入(inject)。
  2. 可以在调用 InvokeAsync 时将参数传递给 View 组件。

我不会在这里讨论这两个功能,因为它们都包含在文档中并且超出了这个问题的范围。

关于c# - 如何在 .NET Core 的主布局 View 中呈现特定 Controller 的 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52447176/

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