2011-05-17 62 views
1

我有一個下拉列表,將不會正確顯示選定的值。它確實具有正確的元素,使用正確的文本和值,但似乎沒有辦法使其實際選擇正確的值。DropdownListFor不會選擇(誰會猜對?)

我所得到的是:

public class StateViewModel { 
    public string Name { get; set; } 
    public string Abbr { get; set; } 
} 

public class ChangeAddressViewModel { 
    //edited down to what's needed 
    public StateViewModel StateViewModel { get; set; } 
    public IEnumerable<StateViewModel> StateViewModels { get; set; } 
} 

我已經試過什麼:

@Html.DropDownListFor(model => model.StateViewModel 
    , Model.StateViewModels.Select(x => new SelectListItem { 
     Text = x.Name, 
     Value = x.Abbr, 
     Selected = x.Abbr == Model.StateViewModel.Abbr 
     }) 
    , @Resource.SelectState) 

//i've stepped through the lambda above and the expression 
//x.Abbr == Model.StateViewModel.Abbr 
//did evaluate to true for one of the iterations 

@Html.DropDownListFor(model => model.StateViewModel 
    , new SelectList(Model.StateViewModels 
    , "Abbr" 
    , "Name" 
    , Model.StateViewModel.Abbr) 
    , @Resource.SelectState) 
+0

在您的視圖頁面上,您的模型定義在頁面頂部? – WEFX 2011-05-17 19:34:50

+0

yup ...我現在正在工作...我將Model.StateViewModel更改爲一個字符串,它保存選定的值而不是選定的對象,出於某種原因,一切都很開心! ? – Mike 2011-05-20 17:02:00

回答

0

我看你指定一個的SelectList:

@Html.DropDownListFor(model => model.StateViewModel 
    , new SelectList(Model.StateViewModels 
    , "Abbr" 
    , "Name" 
    , Model.StateViewModel.Abbr) 
    , @Resource.SelectState) 

這將呈現列表的新實例,而不是您傳入的實例!因此您會這樣做沒有選定的值。

嘗試將其設置爲:

@Html.DropDownListFor(model => model.SelectedStateID, 
         Model.States 
         , new { id = "ddlStates" }) 

而在你的控制器/視圖模型,填充的SelectList如圖below.I寫我自己的例子,因爲它更容易。下面是控制器的代碼中,ActionResult的範圍內:

//Retrieve the list via LINQ/however and also the SelectedStateID 
    var states = .... 

    var statesList = new SelectList(states, "Abbr", "Name", SelectedStateID); 


    var viewModel = new StateViewModel 
    { 
     //assign it to the corresponding ViewModel property 
     States = statesList , 
       ... 
       ... 
    }; 

    return View(viewModel); 

您的視圖模型是這樣的:

private List<SelectListItem> _states = new List<SelectListItem>(); 
    public List<SelectListItem> States 
    { 
     get 
     { 
      return (_states); 
     } 

     set 
     { 
      _states = value; 
     } 
    } 

    public Guid SelectedStateID 
    { 
     get; 
     set; 
    } 

我假設這是你的問題,你沒有想其實有一個新的列表,並且在該列表中選擇一個值作爲默認值。

如果是這樣的話,試試這個:

@Html.DropDownListFor(model => model.StateViewModel 
    , new SelectList(Model.StateViewModels 
        , "Abbr" 
        , "Name") 
, Model.StateViewModel.Abbr 
, @Resource.SelectState) 

我想你的右括號是在錯誤的位置!