I have successfully gotten Visual Studio to generate a drop-down list based on a foreign key between two Models. Each of my "Products" has a "Supplier" value, and so the Products-Create-View now has a SuppliersID drop-down list in it. My classes are:
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; }
}
In my create view for Products, there is the bit of code that creates the HTML select tag and populates it with the SupplierIDs from the database table:
<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>
The drop down list contains "1", "2", "3", etc., showing only the SupplierID field from the Supplier table, but I want to show the Supplier.Name value instead. This way, when adding a new product, the user can select the Supplier by name, rather than the SupplierID. Obvious user-friendliness change.
To be absolutely clear, The value of the tag should remains as the SupplierID, only the content of the tag should be the Supplier Name:
<option value="1">Meat Store</option>
<option value="2">Vegetable Store</option>
<option value="3">Another Supplier</option>
etc.
(I'm sure this is very simple, but I just can't find the syntax I need.)
[Edit] What about a class field attribute that indicates that the Name field is to be the Visible text for the drop down selection? Does that exist?