C# – How Do I Use Entity Object Navigation Properties In A DropDownList On My Strongly Typed ASP.NET MVC Create and Edit Views

asp.netasp.net-mvccentity-frameworknet

I've got an Entity Data Model with Product and Family types. Each Product has one Family.

I'm using this model with an ASP.NET MVC web site. I want Family DropDownLists on the Create and Edit Views of my Product controller.

How Do I Use Entity Object Navigation Properties in a DropDownList on my Strongly Typed ASP.NET MVC Create and Edit Views?

The following code fails…

ProductController:

// POST: /Product/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product p)
{
    db.AddToProduct(p);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Create View:

<p>
    <label for="Family">Family:</label>
    <%= Html.DropDownList("Family", new SelectList((IEnumerable)ViewData["Families"], "Id", "Name"))%>
    <%= Html.ValidationMessage("Family", "*")%>
</p>

Can I do this without using a FormCollection? I would rather keep it a strongly-typed Product.

Best Answer

Right, so you'll be needing something other than your entity object to get the referential lists back. I see you fetching a select list from the ViewData collection bag but don't see it going in. As long as you have it going in either the ViewData or a ViewModel object, you'll be fine.

To the part about your foreign key... as alex stated the current rev of EF doesn't support direct exposure of the foreign keys as simple properties. I believe this is set to change in 2.0 but in the meantime do a search for faking foreign key properties (SO won't allow me to post links yet). It works for me.