views:

680

answers:

3

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.

A: 

Assuming that Product has a Families property (or is a Linq entity with a Foreing Key constraint)

<%= Html.DropDownList("Family", new SelectList(model.Families, "Id", "Name"))%>
Eduardo Molteni
+1  A: 

At present state you can't use foreign keys to make your binding. You have to manualy update a relation between a product and a family. for that you should add a familyid parameter to your "post" action. And assign product.family to families.Where(f=>f.id = famylyId)

Alexander Taran
+1  A: 

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.

JasonCoder