How can i add extra attribute fields to the asp.ne

2019-04-20 22:14发布

问题:

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?

回答1:

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);


回答2:

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);