更改下拉列表以显示与主键不同的字段

Change drop-down list to show different field than the primary key

我已经成功Visual Studio根据两个模型之间的外键生成下拉列表。我的每个 "Products" 都有一个 "Supplier" 值,因此 Products-Create-View 现在有一个 SuppliersID 下拉列表。我的 class 是:

public class Product
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
    public int SupplierID { get; set; }
    public virtual Supplier Supplier { get; set; }
}

public class Supplier
{
    public int SupplierID { get; set; }

    public string Name { get; set; }
    public string Email { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<Product> Product { get; set; }
}

在我的产品创建视图中,有一段代码创建了 HTML select 标签并使用数据库 table 中的 SupplierIDs 填充它:

<div class="form-group">
    <label asp-for="SupplierID" class="control-label"></label>
    <select asp-for="SupplierID" class ="form-control" asp-items="ViewBag.SupplierID"></select>
</div>

下拉列表包含“1”、“2”、“3”等,仅显示来自供应商table的SupplierID字段,但我想要 来显示 Supplier.Name 值。这样,在添加新产品时,用户可以按名称 select 供应商,而不是供应商 ID。明显的用户友好性变化。

绝对清楚,标签的值应该保持为供应商ID,只有标签的内容应该是供应商名称:

<option value="1">Meat Store</option>
<option value="2">Vegetable Store</option>
<option value="3">Another Supplier</option>
etc.

(我确信这很简单,但我就是找不到我需要的语法。)


[编辑] class 字段属性表明名称字段将成为下拉菜单的可见文本 selection 怎么样?存在吗?

查看 https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#the-select-tag-helper 了解使用 select 标签助手的提示。

在那篇参考文献中,他们指出您可以绑定到 SelectListItem 中的 List 以获得您正在寻找的行为。

因此,在您的模型(或 viewbag,如果您使用当前模式)中分配如下内容:(我的目标是从此处的 LINQ 查询获取 IEnumerable。)

ViewBag.SupplierOptions = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "Meat Store" },
            new SelectListItem { Value = "2", Text = "Vegetable Store" },
            new SelectListItem { Value = "3", Text = "Another Supplier"  },
        };

然后这是给你的 select:

<select asp-for="SupplierID" class ="form-control" asp-items="ViewBag.SupplierOptions"></select>

(如链接参考中所述,ViewBag 可能不是最佳选择,但这是另一个问题。)

在你的控制器中:

ViewBag.Suppliers = new SelectList(db.Supplier.ToList(), "Id", "Name");

在您看来:

@Html.DropDownList("SupplierID", (SelectList)ViewBag.Suppliers, "Suppliers...", new { @class = "form-control" })

在 ProductsController class 中,在 Create() 方法中,我找到了创建 SelectList 并将其放入 ViewData 数组的行:

ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierID");

要让名称显示在标签中,我所要做的就是进行一个微小的更改;第三个参数是 DataTextField:

ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "Name");

我知道它必须简单。在这里我正要放弃它。