无法设置强类型 MVC SelectList 的选定值

Trouble setting selected value of strongly typed MVC SelectList

从数据库中获取数据,并添加我打算默认选择的选项:

    public List<Forester> GetForesters()
    {
        var data = _db.tblForester.ToList();

        List<Forester> ForesterList = new List<Forester>();

        foreach (var item in data)
        {
            Person person = new Person()
            {
                Key_ = item.Key_,
                FirstName = item.FirstName,
                LastName = item.LastName,
                District = item.District,
                County = item.County
            };
            PersonList.Add(person);
        }
        PersonList.Add(new Person { Key_ = -1, FirstName = "- Select ", LastName = "Person -" } );
        return PersonList;
    }

模型有两个属性:

    public int SelectedPersonId { get; set; }
    public IEnumerable<SelectListItem> PersonList { get; set; }

控制器从数据库中获取列表并生成一个选择列表:

        vm.SelectedPersonId = -1;
        vm.PersonList = new SelectList(repo.GetPeople(), "Key_", "PersonsName", vm.SelectedpersonId);

我在视图中尝试了几种方法:

                @Html.DropDownListFor(m => m.Key_, new SelectList( Model.PersonList, "Value", "Text", -1), new { @class = "form-control ddl" })

下拉列表效果很好,除了所选值只是列表中的第一个,而不是我指定的值。

HTML 的呈现方式如下:

<form action="/Forester/Activity" method="post"><select class="form-control ddl" data-val="true" data-val-number="The field Key_ must be a number." data-val-required="The Key_ field is required." id="Key_" name="Key_"><option value="1">DIANE PARTRIDGE</option>
<option value="2">GARY GROTH</option>

...

我加的在最下面:

<option value="-1">- Select   Forester -</option>

如果您有以下型号

 public int SelectedPersonId { get; set; }
 public IEnumerable<SelectListItem> PersonList { get; set; }

你应该使用

 @Html.DropDownListFor(m => m.SelectedPersonId , Model.PersonList, new { @class = "form-control ddl" })

DropDownListFor 助手将评估 SelectedPersonId 并尝试 select 它

如果您使用以下内容,最后一个参数指定初始文本(选项标签),因此您不需要使用虚拟 -1 值:

 Html.DropDownListFor(m => m.SelectedPersonId, 
          Model.PersonList as List<SelectListItem>, "Select   Forester -"})

SelectExtensions