views:

440

answers:

1

Hello everybody!

I am facing the problem that I cannot properly map my foreign key table values to an asp.net mvc edit view.

I have placed a Html.DropDownList and made an IENumerable/IQueryable helper function returning:

from item in db.items select item.name

which populates my Html.DropDownList with all the Names in the foreign key table but has nothing in the value field.

But how can I make the DropDownList to show the Names but let the Value field be the ID field of that foreign key table?

+3  A: 

Change the linq-query as follows:

var list = from item in db.items select new {item.id, item.name};

Then create a selectlist as follows:

var items=new SelectList(list, "id","name");

and pass that selectlist to the dropdownlist

Html.DropDownList("name",items)

Bavo
Will that also work for the [Post]Edit function using an id and a formcollection or do I need to tweak it further to also save the new value?
Shaharyar
You need to create a new selectlist with a selected value:>new SelectList(list, "id", "name", itemthatneedstobeselected.id);Be aware that it needs to me the "value" itself, in this case the id, not just an object from your collection.
Bavo
yeap, made it work!Thanks a lot for your help!
Shaharyar