I have many DropDownLists on page
class BigViewModel
{
public List SmallVM {get;set;}
public List Items {get;set;}
//some other properties
}
class SmallViewModel
{
public string ItemId {get;set;}
//some other properties
}
@for( var i = 0;i
{
@Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
}
//display other properties
in controller
bigViewModel.Items = List
{
new SelectListItem{Value = "1", Text = "aaa"},
new SelectListItem{Value = "2", Text = "bbb"},
new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List
{
new SmallViewModel{ItemId = 3},
new SmallViewModel{ItemId = 2},
}
In controller I set diffrent ItemId for every SmallVM and each DropDownList uses the same Items collection. I want to set default Value from SmallViewModel for each DropDownList. For example in this case there are two DropDownLists first should display default text "ccc" and second "bbb".
Should I put diffrent List for every SmallViewModel and set them Selected property or there is other way?
解决方案
This behavior has been reported as a bug on CodePlex but not yet fixed. Using DropDownListFor() in a for loop does not bind correctly and the first option is always selected despite the value of the property. In order for DropDownListFor() to work correctly when using a collection, you need to use an EditorTemplate for the model.
In /Views/Shared/EditorTemplates/SmallViewModel.cshtml
@model SmallViewModel
@Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])
Then in the main view
@model BigViewModel
@using(Html.BeginForm())
{
// Pass the select list to the EditorTemplate as addtionalViewData
@Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
}
You should now have 2 controls displaying "ccc" and "bbb" respectively.