【问题标题】:@Html.DropDownListFor class with collection problem@Html.DropDownListFor 有收集问题的类
【发布时间】:2011-09-09 03:29:05
【问题描述】:

我有一个 viewModel 类“SomeDataViewMode”,该类有“List Schools”对象,其中填充了“School”对象。学校对象具有属性 SchoolID 和名称。 在我看来(剃刀)我补充说:

@Html.DropDownListFor(c => c.ScoolId, new SelectList(Model.Schools), "Select some school")

但我得到的只是下拉列表:

MyProject.Domain.Entities.School

如何获取值?

【问题讨论】:

    标签: asp.net-mvc razor


    【解决方案1】:

    您应该将ToString() 方法添加到School 类,或者使用LINQ 使用Texts 和Values 创建SelectListItems:

    new SelectList(Model.Schools.Select(s => new SelectListItem { Text = s.Name, Value = s.SchoolId }))
    

    编辑:您的代码过于复杂。
    你可以写

    @Html.DropDownListFor(x => x.Schools, new SelectList(list, "SchoolId", "Name"))
    

    【讨论】:

    • 我试过'@Html.DropDownListFor(new SelectList(Model.Schools.Select(s => new SelectListItem { Text = s.Name, Value = s.SchoolId})))'。但它需要第二个参数。
    • 方法 'DropDownListFor' 没有重载需要 1 个参数。但多亏了你的想法,我让这段代码工作了。 @{ List list = Model.Schools; var school = new SelectList(list, "SchoolId", "Name"); } @Html.DropDownListFor(x => x.Schools, @items)
    【解决方案2】:

    您需要指定 School 对象的哪个属性应该用于 Value 以及哪个属性用于 Text。例如,如果 School 模型具有 NameId 属性:

    @Html.DropDownListFor(
        c => c.ScoolId, 
        new SelectList(Model.Schools, "Id", "Name"), 
        "Select some school"
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多