Question

My problem is pretty simple. Lets say I have a dropdown with users. in the database i have 3 fields for my user table:

 user_id
 user_name
 user_firstname

in my MVC app i want to link those users to projects. so thats why i want the dropdown.

now, i want to have a selectlist, with the ID as the value, and the firstname AND lastname to be the 'text'

  SelectList sl = new SelectList(users, "user_id", "user_name");

now how do i get the first name also in the text? this should be fairly easy, but seems it isnt...

Was it helpful?

Solution

Use LINQ to transform your list of users into a list of SelectListItem.

var selectOptions = 
    from u in yourUserQuery
    select new SelectListItem { 
        Value = u.user_id, 
        Text = u.user_firstname + " " + u. user_name 
    };

You can then convert that to a SelectList however you see fit. I personally like to define a .ToSelectList() extension method for IEnumerable<SelectListItem>, but to each his own.

OTHER TIPS

You need to build a list from your database in the format you need. Here is what I did after my database read into a DataTable,

        IList<UsrInfo> MyResultList = new List<UsrInfo>();
        foreach (DataRow mydataRow in myDataTable.Rows)
        {
            MyResultList.Add(new UsrInfo()
            {
                Usr_CD = mydataRow["USR_NR"].ToString().Trim(),
                Usr_NA = mydataRow["USR_NA_LAST"].ToString().Trim() + " , " +
                         mydataRow["USR_NA_FIRST"].ToString().Trim()
            });
        }

        return new SelectList(MyResultList, "Usr_CD", "Usr_NA");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top