How to render action of specific controller in master Layout view in .NET Core?

浪子不回头ぞ 提交于 2020-05-13 13:37:08

问题


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

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

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.

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.

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.


回答1:


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

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

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);
    }
}

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.
*@

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")

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

  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.



来源:https://stackoverflow.com/questions/52447176/how-to-render-action-of-specific-controller-in-master-layout-view-in-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!