下面我可以设置值和文本:
dropListUserImages.DataValueField = "Value";
dropListUserImages.DataTextField = "Text";
dropListUserImages.Items.Add(new ListItem { Text = srText, Value = srValue});
我还想设置额外的属性,例如:
data-imagesrc
data-description
我怎样才能做到这一点?
下面我可以设置值和文本:
dropListUserImages.DataValueField = "Value";
dropListUserImages.DataTextField = "Text";
dropListUserImages.Items.Add(new ListItem { Text = srText, Value = srValue});
我还想设置额外的属性,例如:
data-imagesrc
data-description
我怎样才能做到这一点?
利用:
ListItem test = new ListItem { Text = srText, Value = srValue}
test.Attributes.Add("data-imagesrc", "xxx");
test.Attributes.Add("data-description", "xxx");
dropListUserImages.Items.Add(test);
在将复杂的对象列表转换为可以在前端读取的值时,我遇到了同样的挑战,我使用了类似于下面的逻辑,发现它非常有用,因为它可以适应每种类型的对象:
//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);