2015-03-31 88 views
0

我有一些问题。 我刚刚创建的类名为学生,其具有的其他类对象,它是批处理的C#:如何使用对象填充DropDownList?

public class Student{ 
     public Batch batch {get;set;} 
     public string Name{get;set;} 
     public string CNIC {get;set;} 
} 

,这里是批次类

public class Batch { 
     public string BatchName {get;set;} 
     public int BatchYear {get;set;} 
} 

和我创建了Student类的强类型视图现在怎么样我我应该显示与DropdownListFor方法助手与用户的批处理对象。 在此先感谢。

回答

2

DropDownListFor需要List<SelectListItem>并将其变成列表。因此,您需要构建List<SelectListItem>并将其传递到View Model中的视图。您将无法直接在batch课程中使用DropDownListFor

为了显示批类的下拉列表,你可以试试下面的

public class Student{ 

     public Student() 
     { 
      BatchSelectList = new List<SelectListItem>(); 
      BatchSelectList.Add(new SelectListItem { Text = "Some Label", Value = "Some Val" }; 
     } 

     public Batch batch {get;set;} 
     public string Name{get;set;} 
     public string CNIC {get;set;} 

     //Drop down properties used in view 
     public String BatchSelectedItem { get; set; } 
     public List<SelectListItem> BatchSelectList { get; set; } 
} 

通过上述,您正在建设将在列表中选择该项目的占位符,BatchSelectedItem ,并且您还在构建将在视图中使用的选择列表。

在您看来,您将需要以下内容。

@Html.DropDownListFor(x => x.BatchSelectedItem, Model.BatchSelectList) 

当第一个选项是什么属性的选择列表必然,第二个属性是填充对象列表中DropDownListFor

-1

您可以在学生模型

创建批处理列表
public class Student{ 
     public Batch batch {get;set;} 
     public string Name{get;set;} 
     public string CNIC {get;set;} 
     public List<Batch> batchList {get;set;} 
} 

然后在你的模型,你可以设置你的DropDownList为:

@Html.DropDownListFor(model => model.batch, new SelectList(Model.batchList,"BatchYear","BatchName")) 

在上面的代码中,您设置了批处理女巫的DDL由batchList填充,显示BatchName并将值设置为BatchYear。

+0

您无法将“