DropDownList如何选择默认值

时间:2015-02-13 20:10:53

标签: c# asp.net-mvc

我在页面上有很多DropDownLists

class BigViewModel
{
    public List<SmallViewModel> SmallVM {get;set;}
    public List<SelectListItem> Items {get;set;}
    //some other properties
}
class SmallViewModel
{
    public string ItemId {get;set;}
    //some other properties
}

<table>
    @for( var i = 0;i<Model.SmallVM.Count();i++)
    {
        <tr>
            <td>
                @Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
            </td>        
        </tr>       
    }
//display other properties
</table>
控制器中的

bigViewModel.Items = List<SelectListItem>
{
    new SelectListItem{Value = "1", Text = "aaa"},
    new SelectListItem{Value = "2", Text = "bbb"},
    new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List<SmallViewModel>
{
    new SmallViewModel{ItemId = 3},
    new SmallViewModel{ItemId = 2},
}

在控制器中,我为每个SmallVM设置了不同的ItemId,每个DropDownList使用相同的Items集合。我想为每个DropDownList设置SmallViewModel的默认值。例如,在这种情况下,有两个DropDownLists首先应该显示默认文本&#34; ccc&#34;第二个&#34; bbb&#34;。

我应该为每个SmallViewModel添加不同的List<SelectedListItem>并将它们设置为Selected属性还是有其他方法?

2 个答案:

答案 0 :(得分:1)

此行为已报告为CodePlex上的错误,但尚未修复。在DropDownListFor()循环中使用for无法正确绑定,并且始终选择第一个选项,尽管该属性的值。为了使DropDownListFor()在使用集合时正常工作,您需要为模型使用EditorTemplate

/Views/Shared/EditorTemplates/SmallViewModel.cshtml

@model SmallViewModel
@Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])

然后在主视图中

@model BigViewModel
@using(Html.BeginForm())
{
  // Pass the select list to the EditorTemplate as addtionalViewData
  @Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
  <input type="submit" />
}

您现在应该有2个<select>控件显示&#34; ccc&#34;和&#34; bbb&#34;分别

答案 1 :(得分:0)

根据您的代码更新,我认为您只需将视图代码修改为:

@Html.DropdownListFor(m=> m.SmallVM[i].ItemId, Model.Items)

然而,我有一种明显的感觉,这是一个非常XY problem,虽然这种改变会使一切都在发布,但你仍然不会得到你真正需要的东西。你试图解决的真正问题。