简体   繁体   English

如何将数组从控制器传递到_layout.cshtml

[英]How to pass an array from controller to _layout.cshtml

I have to pass an array to my _layout page (which does not have an @model). 我必须将一个数组传递到我的_layout页面(该页面没有@model)。 The array must come from an controller method such as: 该数组必须来自控制器方法,例如:

public IActionResult AssignLoan()
    {

        EntityDetails entity = new EntityDetails();
        entity.Name = (from o in _context.EntityDetails
                       select o.Name).ToString();



        entity.Name.ToArray();
        ViewData["populatedropdown"] = entity;

        return View();
    }

and the array must be passed to this section of the _layout view and must be set equal to var countries. 并且必须将数组传递到_layout视图的此部分,并且必须将其设置为等于var国家。

  var countries = ["Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa"];

Use a view component. 使用视图组件。 Add a folder called ViewComponents to your project and add the following class. 在您的项目中添加一个名为ViewComponents的文件夹,并添加以下类。 Obviously, change Foo to a name that actually describes what this does. 显然,将Foo更改为一个实际描述此功能的名称。

public class FooViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        var list = // get your list
        return View(list);
    }
}

Then, add a view at Views\\Shared\\Components\\Foo\\Default.cshtml . 然后,在Views\\Shared\\Components\\Foo\\Default.cshtml添加一个视图。 Inside, put the HTML that renders you drop down list. 在内部,放入呈现您的HTML下拉列表。

Finally, in your layout: 最后,在您的布局中:

@await Component.InvokeAsync("Foo")

Where "Foo" is the name of your view component minus the ViewComponent part. 其中"Foo"是视图组件的名称减去ViewComponent部分。 View components are injectable, so if you need access to your context or something, you simply add a constructor that receives that as a param and assign it to an ivar, just as you would with a controller. View组件是可注入的,因此,如果您需要访问上下文或其他内容,则只需添加一个构造函数即可,将其作为参数接收,并将其分配给ivar,就像使用控制器一样。 Also, InvokeAsync can be passed parameters if you need them. 另外,如果需要,可以向InvokeAsync传递参数。 For example: 例如:

public async Task<IViewComponentResult> InvokeAsync(string foo)

And then: 接着:

@await Component.InvokeAsync("Foo", new { foo = "bar" })

More information can be found in the docs . 可以在文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM