更改下拉列表以显示与主键

时间:2017-10-10 22:35:22

标签: c# asp.net-mvc html-select

我已经成功地让Visual Studio根据两个模型之间的外键生成一个下拉列表。我的每个“产品”都有一个“供应商”值,因此Products-Create-View现在有一个SuppliersID下拉列表。我的课程是:

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标记,并使用数据库表中的SupplierID填充它:

<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”等,仅显示Supplier表中的SupplierID字段,但我希望显示Supplier.Name值代替。这样,在添加新产品时,用户可以按名称而不是SupplierID选择供应商。显而易见的用户友好性变化。

要绝对清楚,标签的值应保留为SupplierID,只有标签的内容应为供应商名称:

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

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

[编辑]类字段属性如何指示名称字段是下拉选择的可见文本?那存在吗?

3 个答案:

答案 0 :(得分:1)

请查看https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#the-select-tag-helper,了解有关使用选择标记帮助程序的提示。

在该引用中,他们指出您可以绑定List SelectListItem来获取您正在寻找的行为。

所以在你的模型中(如果使用当前模式,则为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 asp-for="SupplierID" class ="form-control" asp-items="ViewBag.SupplierOptions"></select>

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

答案 1 :(得分:1)

在您的控制器中:

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

在您看来:

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

答案 2 :(得分:0)

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

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

所有我必须做的就是让标签显示在标签中是为了做一个微小的改变;第三个参数是DataTextField:

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

我知道它必须是简单的东西。在这里,我即将放弃它。