DropDownListFor不会在视图中获取选中的项目,而是在视图模型中
本文关键字:视图 模型 项目 获取 DropDownListFor | 更新日期: 2023-09-27 18:06:57
我在我的视图中使用了一个下拉列表帮助器:
@Html.DropDownListFor(m => m.BasePlayerForm.Position, Model.GetPositions())
我在模型中有一个函数填充列表:
public IEnumerable<SelectListItem> GetPositions()
{
foreach (string positionValue in Enum.GetNames(typeof(PlayerPosition)))
{
var selectListItem = new SelectListItem();
selectListItem.Text = positionValue;
selectListItem.Value = ((int)Enum.Parse(typeof(PlayerPosition), positionValue)).ToString();
if (BasePlayerForm.Position.ToString() == positionValue)
selectListItem.Selected = true;
yield return selectListItem;
}
}
(我知道还有一个更短的版本,返回一个列表项,但出于调试目的,我发现这更有用。)有趣的是,如果我在"selectListItem"上放一个断点。"行,调试器会选中它,但是当我呈现视图时,没有选择选项。在我的视图中,我还使用了另一个下拉列表作为helper,与填充下拉列表的方式相同,但那个下拉列表获得了选中的项。我真不知道有什么问题。如果有人知道,请告诉我,我将非常感激=)
当使用强类型的Html helper时,将SelectListItem的IEnumerable作为参数,这些项的选定属性将被忽略。
当你在GetPositions()方法中设置SelectListItem的值时,你正在将PlayerPosition enum转换为int。我假设BasePlayerForm。视图模型中的Position属性不是int。如果你改变BasePlayerForm。选择项的位置为int,应根据该属性进行设置。
您可以在property:
中使用该代码,而不是使用函数:public IEnumerable<SelectListItem> ChangeMyName {
get {
foreach (string positionValue in Enum.GetNames(typeof(PlayerPosition)))
{
var selectListItem = new SelectListItem();
selectListItem.Text = positionValue;
selectListItem.Value = ((int)Enum.Parse(typeof(PlayerPosition), positionValue)).ToString();
if (BasePlayerForm.Position.ToString() == positionValue)
selectListItem.Selected = true;
ChangeMyName.Add(selectListItem);
}
set{return;}
}
那么,你可以这样调用它:
@Html.DropDownListFor(m => m.BasePlayerForm.Position,new SelectList( Model.GetPositions)
我不确定这是否有帮助,但这将是我要尝试的。