DropDownList在两个类的包装类中

时间:2011-03-13 10:03:57

标签: asp.net-mvc

当我包装三个课程时,我的问题就开始了 第一堂课是

[Bind(Exclude="ID")]
public class Material 
{
   public string MaterialName { get; set; }
}

第二堂课是

[Bind(Exclude="ID")]
public class ExameState 
{
    public string ExamState { get; set; }
}

第三节是

[Bind(Exclude="ID")]
public class Exams
{
    public string ExamsName { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime StartingDate { get; set; }
    public int Period  { get; set; }
    public int ExamStateID { get; set; }
    public int MaterialID { get; set; }
    public int GroupID { get; set; }
    public int QuestionState { get; set; }
    public int TeacherID { get; set; }
    public int ExamMarkState { get; set; }
    public string Password { get; set; }
}

包装类是

public class Examswrapper
{
    public Material material { get; set; }
    public ExameState examstate { get; set; }
    public Exam exam { get; set; } 
}

我需要显示材质的下拉列表,其中datavalue = MaterialName 和key = ID在视图上构建在Examswrapper类上 我正在尝试这个

如何制作它 并感谢您的建议

新错误: System.NullReferenceException:未将对象引用设置为对象的实例。

2 个答案:

答案 0 :(得分:0)

@Html.DropDownListFor(model => model.material,
        Model.material.Select(
        x => new SelectListItem
        {
            Text = x.MaterialName,
            Value = x.Id
        }
    ))

答案 1 :(得分:0)

您的视图模型存在问题,因为如果您需要下拉列表,Material属性应该是一个集合。您的Material类也缺少ID属性。所以:

public class Material 
{
   public string ID { get; set; }
   public string MaterialName { get; set; }
}

public class ExamsViewModel
{
    public string SelectedMaterialId { get; set; }
    public IEnumerable<Material> Materials { get; set; }

    ... // some other properties
}

然后在你的强类型视图中:

<%= Html.DropDownListFor(
    // This is the property that will hold the selected value
    x => x.SelectedMaterialId,
    // Build the select list based on the Model.Materials collection
    new SelectList(
        Model.Materials.Select(material => new SelectListItem 
        {
            Value = material.ID,
            Text = material.MaterialName
        }),
        "Value", "Text"
    )
) %>