Masriyah
Masriyah

Reputation: 2505

creating a list from dropdown option

i have a dropdown list labeled status and i wanted to add the following options to the drop down:

Open
Closed
All

for each option a stored procedure will be used generate the results. I just blanked on how add options to the dropdown list without populating them from a table.

Asp.net project, mvc/c#

Upvotes: 2

Views: 1976

Answers (3)

Masriyah
Masriyah

Reputation: 2505

after looking at Ray K. sample i was able to form the following which i think flows with how the rest of my dropdown boxes are displayed:

viewModel.Status = new[]
                               {
                                   new SelectListItem {Text = "All", Value = "0"},
                                   new SelectListItem {Text = "Open", Value = "1"},
                                   new SelectListItem {Text = "Closed", Value = "2"},
                               };
        return viewData;

Thanks again Ray K.

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53685

No need to write space constructions for the simple things, just plain html.. :

<select id="selectId" name="selectName">
  <option value="0" selected="">Open</option>
  <option value="1">Closed</option>
  <option value="2">All</option>
<select>

So, i see only one reason to add List of SelectListItem to a model -- if you want use DataAnnotations for validation.

Upvotes: 0

Ray K.
Ray K.

Reputation: 66

    <asp:DropDownList ID="ddlExample" runat="server">
        <asp:ListItem Text="Open"></asp:ListItem>
        <asp:ListItem Text="Closed"></asp:ListItem>
        <asp:ListItem Text="All"></asp:ListItem>
    </asp:DropDownList>

If you want to specify a different value, you can delcare that within the ListItem row

... If you need to add in the code behind:

        ddlExample.Items.Insert(0, new ListItem("Open"));
        ddlExample.Items.Insert(1, new ListItem("Closed"));
        ddlExample.Items.Insert(2, new ListItem("All"));

Upvotes: 2

Related Questions