amarcy
amarcy

Reputation: 1515

Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem

I have a table that contains a list of EquipmentIDs and another table that has maintenance records.

When the user edits a maintenance record I want there to be a drop down list of all of the equipment IDs from the table.

The dropdown list populates, and it populates with the correct amount of entries, however they all say System.Web.MVC.SelectListItem instead of the value of the ID.

Here is the code that generates the list:

public ActionResult Edit(int id)
{
    MaintPerformed maintPerformed = maintPerformedRepository.GetMaintPerformed(id);

    IList<EquipmentID> IDs = equipmentIDRepository.GetEquipmentIDAsList();

    IEnumerable<SelectListItem> selectEquipList =  
        from c in IDs
        select new SelectListItem
        {
            //Selected = (c.EquipID == maintPerformed.EquipID),
            Text = c.EquipID,
            Value = c.Sort.ToString()
        };

    ViewData["EquipIDs"] = new SelectList(selectEquipList, maintPerformed.ID);
    return View(maintPerformed);
}

Here is the entry in the .aspx page for the Dropdown list:

%: Html.DropDownList("EquipIDs") %>

Here is how I am generating the list from the table:

public List<EquipmentID> GetEquipmentIDAsList()
    {
        return db.EquipmentIDs.ToList();
    }

It appears that everything is working correctly with the exception of assigning the text to be displayed in the drop down box.

What am I missing or not thinking correctly about?

Upvotes: 11

Views: 7837

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77536

SelectList and SelectListItem are actually mutually exclusive. You should be using one or the other. Etiher pass the constructor of SelectList your raw data (IDs) or don't use SelectList at all and just make ViewData["EquipIDs"] your enumerable of SelectListItem. If you go with the latter approach, you will have to tweak your code so that you are setting the selected item in the constructor of SelectListItem (as you had done, but commented out).

Either:

ViewData["EquipIDs"] = new SelectList(IDs, maintPerformed.ID, "EquipID", "Sort");

Or:

IEnumerable<SelectListItem> selectEquipList =
    from c in IDs
    select new SelectListItem
    {
        Selected = c.EquipID == maintPerformed.EquipID,
        Text = c.EquipID,
        Value = c.Sort.ToString()
    };

ViewData["EquipIDs"] = selectEquipList;

Upvotes: 33

Related Questions