简体   繁体   English

在 Layout 中渲染局部视图并在 asp.net core 中为其声明一个控制器

[英]Rendering a partial view in Layout and declare a controller for it in asp.net core

I have the following scenario我有以下场景

 @model CashUnited.Models.HomeViewModel   
 <html lang="en">
 <head>
   <title>@ViewData["Title"] - test</title>
 </head>
 <body>
   <partial name="_Header" model="@Html.DisplayNameFor(model=>model)"/>
 </body>
</html>

my partial view Code我的部分视图代码

<select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
}                 

How and where I can Fill Model.companiesLst from the controller?我如何以及在哪里可以从控制器填充Model.companiesLst I can't seem to figure it out in asp.net Core我似乎无法在 asp.net Core 中弄清楚

You have to create/get instances of your model and then pass it to the main view like this:您必须创建/获取模型的实例,然后将其传递给主视图,如下所示:

public ActionResult GetItems() {
    var items = this.itemsService.GetItems();

    return this.View(items);
}

Where variable with name items is your model which contains the property companiesList .其中带有名称items 的变量是您的模型,其中包含属性companyList

The parent view:父视图:

@model CashUnited.Models.HomeViewModel   
 <html lang="en">
 <head>
   <title>@ViewData["Title"] - test</title>
 </head>
 <body>
   @await Html.PartialAsync("_Header", Model)
 </body>
</html>

The partial view:部分观点:

@model CashUnited.Models.HomeViewModel

<select>
@{
   foreach (string item in Model.companiesLst)
   {
      <option value="@item">@item</option>
   }
} 
</select> 

Check out this answer: https://stackoverflow.com/a/52470112/6694514 .看看这个答案: https : //stackoverflow.com/a/52470112/6694514 It seems to fix a similar issue to the one you are having.它似乎解决了与您遇到的问题类似的问题。

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

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