如何从 Razor 中的不同模型填充下拉列表?

How do I populate a dropdown from a different model in Razor?

我正在从事一个项目,其中有一个主模型需要包含许多其他模型并将它们显示在主模型的视图中。我似乎无法从他们那里获取我需要在下拉列表中填充的数据。

我的一个较小的模型是 Entity,看起来像这样:

   public class Entity
{
    //[Required]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Active { get; set; }
}

这是我试图将选择列表项引入的标记语言:

<div class="form-group">
                    <label asp-for="SecurityLog.EntityID" class="control-label"></label>
                    <select asp-for="SecurityLog.EntityID" class="form-control switch-disable" asp-items="EntityID">
                        <option value="">--Select Entity--</option>
                    </select>
                    <span asp-validation-for="SecurityLog.EntityID" class="text-danger"></span>
                </div>

在我的 EditModel 页面上,我创建了一个实体 viewData,但无法让结果显示在标记中。它被称为 "EntityID":

            ViewData["EntityID"] = new SelectList(_context.Entity.Where(a => a.Active == "Y"), "ID", "Name");

我似乎无法让 ViewData 显示任何内容,并且一直在尝试整个下午的大部分时间。提前致谢!

你很接近...

可以通过 ViewBag 在剃须刀页面上访问 ViewData 实体 ID 属性。

剃刀页面

<select id="entity" asp-for="SecurityLog.EntityID" class="form-control" asp- 
        items="ViewBag.EntityID">
    <option value="">--Select Entity--</option>
</select>

OnGetAsync

ViewData["EntityID"] = new SelectList(_context.Entity.Where(a => a.Active == "Y"), "ID", "Name");