Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i add extra attribute fields to the asp.net dropdown list

Below I am able to set values and the text:

dropListUserImages.DataValueField = "Value";
dropListUserImages.DataTextField = "Text";
dropListUserImages.Items.Add(new ListItem { Text = srText, Value = srValue});

I also want to set extra attributes such as:

data-imagesrc
data-description 

How can I do that?

like image 769
MonsterMMORPG Avatar asked Jan 09 '13 02:01

MonsterMMORPG


2 Answers

Use:

ListItem test  = new ListItem { Text = srText, Value = srValue}
test.Attributes.Add("data-imagesrc", "xxx");
test.Attributes.Add("data-description", "xxx");
dropListUserImages.Items.Add(test);
like image 110
Nix Avatar answered Oct 07 '22 19:10

Nix


I've had the same challenge with translating complex lists of object into values that can be read on the front end, I've used logic similar to the below and found it very useful because it can be adaptive for every type of object:

//Object can be whichever type as you wish
List<Object> example = new List<Object>();

var listItemExamples = example
    .Select(a => new Func<ListItem>(() => {
                ListItem item = new ListItem(a.PropropertyA.ToString(), a.PropropertyB.ToString() );
                item.Attributes["data-PropropertyC"] = a.PropropertyC.ToString();
                return item;
            })())
    .ToArray();

dropListUserImages.Items.AddRange(listItemExamples);
like image 26
David Rogers Avatar answered Oct 07 '22 21:10

David Rogers