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

2019-04-20 21:48发布

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?

2条回答
劳资没心,怎么记你
2楼-- · 2019-04-20 22:08

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);
查看更多
Explosion°爆炸
3楼-- · 2019-04-20 22:16

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);
查看更多
登录 后发表回答