Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind list to dropdownlist, what to do with value?

I am binding a List to a DropDownList. But I want to give other values to the value per list item.

I have following ddl and list:

List<string>

sport, volleyball, rugby

<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="sport">sport</option>
    <option value="volleyball">volleyball</option>
    <option value="rugby">rugby</option>
</select>

But I want following (ID in the value)

<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="1">sport</option>
    <option value="2">volleyball</option>
    <option value="3">rugby</option>
</select>

How do I need to create a List so I can get the above dropdownlist.

Thanks

like image 298
Ozkan Avatar asked Dec 22 '11 09:12

Ozkan


People also ask

How do you bind a dropdown value?

Data binding can be achieved by using the bind-Value attribute and it supports string, int, Enum and bool types. If component value has been changed, it will affect all the places where you bind the variable for the bind-value attribute.

Which property on a DropDownList do you set with a column name?

Local Data Specify the column names in the Fields property.

How do you bind a static value to a DropDownList in MVC?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


2 Answers

If you are able to change the type of your source I would recommend to use a dictionary. You can do it this way:

var source = new Dictionary<int, string>();
source.Add(0, "Sports");
source.Add(1, "Football");
dropDown.DataSource = source;
dropDown.DataTextField = "Key";
dropDown.DataValueField = "Value";
dropDown.DataBind();

This would lead to this:

<select name="DdlCat2" id="DdlCat2" class="cats">
    <option selected="selected" value="Sports">0</option>
    <option value="Football">1</option>
</select>

Later you can access the ID or value like this:

dropDown.SelectedItem.Value
dropDown.SelectedItem.Text
like image 180
LMW-HH Avatar answered Sep 28 '22 02:09

LMW-HH


What you could do is to create the ListItems manually like this:

List<string> yourValues;
for(var i=0; i < yourValues.Count; i++)
    YourDropDown.Items.Add(new ListItem(yourValues[i], i.ToString());

Or you could create a temporary variable and bind your drop down list with a linq query, like this:

List<string yourValues;
var index = 0;
YourDropDown.DataSource = yourValues.Select(x => new { Text = x, Value = index++ });
YourDropDown.DataBind();

and combine that with the markup:

<asp:DropDownList ID="YourDropDown" DataValueField="Value" DataTextField="Text" runat="server" />
like image 35
A. Tapper Avatar answered Sep 28 '22 03:09

A. Tapper