![](/img/trans.png)
[英]Populate Drop Down List from IEnumerable in the Model, Set Selected Value
[英]getting selected value of IEnumerable<T> from Drop Down List
我有一個下拉列表,如下所示:
DropDownList1.DataSource = Students.GetStudents();
DropDownList1.DataBind();
-----------
我有一個DataAccess類,如下所示:
public IEnumerable<StudentEntity> GetStudents()
{
List<StudentsEntity> studentsList = new List<StudentsEntity>();
studentsList = Service.GetList() // some service getting a list of sutdents
return new BindingList<StudentEntity>(studentsList);
}
我有一個DataObject類,如下所示:
public class StudentEntity : IComparable
{
public string fullname { get {return firstName +", "+ lastName;}
public string ID {get; set;}
public string Height {get; set;}
public string Firstname {get; set;}
public string Lastname {get; set;}
public int CompareTo(object obj)
{
StudentEntity entity = (StudentEntity) obj;
return Lastname.CompareTo(entity.Lastname);
}
}
在UI級別-“學生全名”顯示在下拉列表中,因此如何從下拉列表中獲取所選學生的“ ID”?
從DropDownList獲取所選項目,並將其轉換為StudentEntity類型的對象。 之后,您可以獲取該對象的ID。 偽代碼:
var selectedItem = myDropDown.SelectedItem as StudentEntity;
var ID = selectedItem.ID;
編輯:
“ hvd”正確地評論了我。 由於這是在網絡環境中進行的,因此您必須實現一些不同。 您可以設置DropDownList的DataTextField和DataValueField。 將ID綁定到DataValueField,並在獲得SelectedItem時,獲得Value-property,然后獲得ID。
var selectedItem = myDropDown.SelectedItem;
var ID = selectedItem.Value;
在事件處理程序中:
var id = ((StudentEntity)sender).Id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.