Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

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?

like image 851
amarcy Avatar asked Sep 30 '10 16:09

amarcy


People also ask

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.


1 Answers

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;
like image 76
Kirk Woll Avatar answered Sep 24 '22 03:09

Kirk Woll