我有一个Site类,该类具有3个属性(facility_id,facility_name和facility_code)。我想知道是否可以将其绑定到下拉列表,以便在选择选项时可以访问所有3个属性。出于测试目的,我只是硬编码utility_code =“ ASV”。
List<Site> sites = new List<Site>();
string responseString = response.Content.ReadAsStringAsync().Result;
sites = JsonConvert.DeserializeObject<List<Site>>(responseString);
Site defaultSite = new Site { facility_id = -1, facility_name = "" };
sites.Insert(0, defaultSite);
sites = sites.Select(x => new Site { facility_id = x.facility_id, facility_name = x.facility_name, facility_code = "ASV" }).ToList();
dropDownSites.DataValueField = "facility_id";
dropDownSites.DataTextField = "facility_name";
dropDownSites.DataSource = sites;
dropDownSites.DataBind();
下面是我不知道如何访问每个站点属性的地方。我收到一个错误消息:“无法将类型ListItem转换为网站...)
string facilityCode = (dropDownSites.SelectedItem as Site).facility_code.ToString();
答案 0 :(得分:2)
否,您不能绑定多个属性。您必须在facility_id
列表中以sites
的SelectedValue进行PostBack之后再次找到正确的项目。
但是,如果您确实希望将所有属性放在一个字符串中,请将其作为DataValueField
,然后在PostBack上再次拆分该字符串。因此,创建一个额外的属性,以单个字符串返回所有属性。尽管这可行,但这并不是最干净的解决方案。
public class Site
{
public int facility_id { get; set; }
public string facility_name { get; set; }
public string facility_code { get; set; }
public string facility_DataValueField
{
get
{
return facility_id + ";" + facility_name + ";" + facility_code;
}
}
}
现在您可以将该属性用作DataValueField
dropDownSites.DataValueField = "facility_DataValueField";
然后在PostBack上,您可以拆分DataValueField以再次获取值。
string [] properties = dropDownSites.SelectedValue.Split(';');