本文介绍了如何在.NET Core的主布局视图中呈现特定控制器的动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling "TopNav" partial from within Layout master view.

我希望对TopNav视图进行强类型输入,并希望在TopNavController中创建模型.

I want TopNav view to be strongly typed and the model to be created within TopNavController.

有什么方法可以从主视图中呈现特定控制器的动作?因此,在这种情况下,我需要在Layout中呈现TopNavControllerTopNav操作.

Is there any way to render the action of a specific controller from within the master view? So in this case I need to render TopNav action of TopNavController in the Layout.

到目前为止,我只能使用例如. @Html.Partial("TopNav")@Html.RenderPartial("TopNav")具有通过模型的选项,但我需要在控制器内实例化模型.

So far I can only use eg. @Html.Partial("TopNav") or @Html.RenderPartial("TopNav") with option to pass the model but I need to instantiate the model within the controller.

以前的版本中曾经有Html.Action("Action", "Controller")帮助器,但是.NET Core中似乎不再提供它.

There used to be Html.Action("Action", "Controller") helper in previous versions but it doesn't seem to be available any more in .NET Core.

推荐答案

在GitHub问题中,对为什么 @Html.Action(..)的很好解释是为什么@ Html.Action被删除了?.

There's a good explanation of why @Html.Action(..) was removed in a GitHub issue here: Why was @Html.Action removed?.

给出该建议,很明显,您的示例的建议是创建一个查看组件,按照约定将其命名为TopNavViewComponent.

Given that advice, it's clear that the recommendation for your example would be to create a View Component, which would be named TopNavViewComponent by convention.

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文件.这是该文件的外观示例(其预期位置以粗体显示):

The call to View looks for a Default.cshtml Razor file in a known location. Here's an example of what that file would look like (its expected location is in bold):

Shared/Components/TopNav/Default.cshtml

@model YourModelClassType

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

要使用此新的视图组件,请将以下内容添加到您的Layout视图中,无论您希望呈现输出的位置是什么:

To use this new View Component, add the following into your Layout view, wherever you want the output to be rendered:

Shared/_Layout.cshtml

@await Component.InvokeAsync("TopNav")

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

That should be enough to get you started with View Components. A couple of other useful things to know are:

  1. View组件支持依赖项注入.
  2. 调用InvokeAsync时可以将参数传递到视图组件中.
  1. View Components support dependency injection.
  2. Arguments can be passed into a View Component when calling InvokeAsync.

在这里,我将不介绍这两个功能,因为它们全部都包含在文档中,并且不在此问题的范围之内.

I won't go into those two features here as it's all covered in the documentation and is outside of the scope of this question.

这篇关于如何在.NET Core的主布局视图中呈现特定控制器的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:13