This is taken from VS Add New Scaffolded Item... when creating a new controller.
In the controller:
// GET: Drivers/Create
public ActionResult Create()
{
ViewBag.Tenant = new SelectList(db.Tenants, "TenantID", "TenantName");
return View();
}
The view then renders a drop-down list:
@Html.DropDownListFor(model => model.Tenant, null, htmlAttributes: new { @class = "form-control" })
The relevant model information:
public partial class Driver
{
public int DriverID { get; set; }
public int Tenant { get; set; }
public virtual Tenant Tenant1 { get; set; }
}
public partial class Tenant
{
public Tenant()
{
this.Drivers = new HashSet<Driver>();
}
public int TenantID { get; set; }
public string TenantName { get; set; }
public virtual ICollection<Driver> Drivers { get; set; }
}
Can someone explain why this works?
I looked at other questions and documentation and couldn't find the answer. I suspect it is something along the lines of "convention over configuration" and it is pulling from the ViewBag using the name of the property. In fact, I changed the ViewBag property to Tenantz and got the following exception:
There is no ViewData item of type 'IEnumerable' that has the key 'Tenant'.
So is setting the property name of the ViewBag the same as the model property you want to update a good practice? It seems ok but I always hear how you should avoid ViewBag and dynamic types.