How to use object navigation properties of an object in DropDownList on my strongly typed ASP.NET MVC Create and edit views?

I have an entity data model with product types and families. Each product has one family.

I am using this model with an ASP.NET MVC website. I want Family DropDownLists to create and edit views of my product controller.

How to use object navigation properties of an object in DropDownList on my strongly typed ASP.NET MVC Create and edit views?

The following code does not work ...

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 FormCollection? I would rather keep it a strongly typed product.

+4
source share
3 answers

You cannot currently use foreign keys to create a binding. You must manually update the relationship between the product and the family. To do this, you should add the familyid parameter to the "post" action. And assign product.family to the families. Where (f => f.id = famylyId)

+1
source

That's right, so you'll need something other than the object of the object to return the reference lists. I see that you select a select list from the ViewData collection package, but you don’t see how this happens. As long as you do this in a ViewData or ViewModel, everything will be fine.

Regarding your foreign key ... since alex stated that the current EF turnover does not support the direct effect of foreign keys as simple properties. I believe that this will change in version 2.0, but at the same time do a search to falsify the properties of the foreign key (SO will not allow me to post links yet). This works for me.

+1
source

Assuming the Product has a Families property (or is a Linq object with a Foreing Key constraint)

 <%= Html.DropDownList("Family", new SelectList(model.Families, "Id", "Name"))%> 
0
source

All Articles