Faizan S.
Faizan S.

Reputation: 8644

Populating Html.DropDownList with foreign key table vlaues

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?

Upvotes: 1

Views: 2868

Answers (1)

Bavo
Bavo

Reputation: 431

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)

Upvotes: 3

Related Questions