Steve
Steve

Reputation: 923

Razor form with dropdown list

Help me understand how to construct this. Everyone and every example on the INet seems to think the only purpose of a Razor v3 asp.net form page that utilizes a DropDownList to have no other purpose but to present the drop down on the page absent any other context.

What I am doing is building a data entry page to enable a user to create a record of an Item ... think pencils, or socks, or cars ... in a database. Two, but not the only, attributes of an Item are 1) it's order quantity {1, 2, 3, ...} and ...here is where my trouble starts... 2) it's unit of measure, UOM, {Each, Case, Weight, ...}

I have a page that has a model for the Item. And this works just fine. Now I'm trying to change the UOM field on the page from a TextBoxFor() to a DropDownList().

How do I populate the drop down with a discreet list of options based on UOMModel where the page is based on ItemModel?

Upvotes: 1

Views: 158

Answers (1)

DCruz22
DCruz22

Reputation: 806

As @Brian Mains said in his comment you need to convert the data to the SelectList class in order to use it with a DropDownList. You can do this:

    public SelectList GetSelectList(List<UOMModel> model)
    {

        var selectListItem = new List<SelectListItem>();

        foreach (var item in model)
        {
            selectListItem.Add(new SelectListItem { Value = item.Value, Text = item.Text});
        }

        return new SelectList(selectListItem, "Value", "Text");
    }

Then use a ViewBag to pass it to your View:

//Action
ViewBag.UOMList = GetSelectList(UOMList);

//View
@Html.DropDownList("UOM", ViewBag.UOMList as SelectList, new { })

Upvotes: 3

Related Questions