我有一个下拉列表,无法正确显示所选值。它确实包含正确的元素,使用了正确的文本和值,但似乎没有办法让它实际选择正确的值。
我得到的是:
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 :(得分: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" })
在你的Controller / ViewModel中,填充SelectList,如下所示。我写了我自己的例子,因为它更容易。下面是ActionResult中的Controller代码:
//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);
您的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)
我认为你的右支撑位置错误!