Reputation: 77
I have tried a lot of different solutions online, but I haven't been able to find any solutions which implement the solution I am looking for correctly.
I want to combine two attributes of a table, these being FirstName and LastName, and then I want to display these coupled attributes as a dropdownlist for the user to choose. I've also tried using SelectListItem, but that has only resulted in errors and I was unable to compile.
So far, my solution involves this:
In my controller:
var data =
from p in db.Contacts
select new
{
FirstName = p.FirstName,
LastName = p.LastName
};
SelectList personList = new SelectList(data, "FirstName", "LastName");
In my View:
@Html.DropDownList("ContactName", (SelectList)ViewBag.Names)
The output of this is a drop down containing options that are in this format:
{ FirstName = Joe, LastName = Bloggs }
Any help would be appreciated.
Upvotes: 1
Views: 69
Reputation: 14133
You need to concatenate the 2 field into one.
var data =
from p in db.Contacts
select new
{
Name = p.FirstName + " " + p.LastName,
Id = p.IdContact
};
SelectList personList = new SelectList(data, "Id", "Name");
With the code above you will achieve what you need.
But read this answer on how to better work with DropDownLists: https://stackoverflow.com/a/20008816/7720
Upvotes: 1