且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SelectList中的选定项未显示在视图下拉列表中

更新时间:2021-07-24 22:24:45

这个问题过去曾咬过我几次,一直追溯到MVC 3左右.

This one has bitten me a few times in the past, all the way back to MVC 3 or so.

基本上,如果要将模型传递给视图(即使用 @model MyTypeOfViewModel 指令)并将 select 绑定到该模型的属性,则选择列表的选定值是要在视图模型上绑定到的属性的.直接在选择列表中设置选择的项目将被忽略.

Basically, if you're passing a model to your view (i.e. using a @model MyTypeOfViewModel directive) and binding a select to a property on that model, then the selected value of the select list is the value of the property you are binding to on your view model. Setting the selected item in a select list directly will be ignored.

在您的情况下,它是 SeasonID 的来源:

In your case, it's SeasonID from this:

<select asp-for="SeasonID" ...>

因此,要选择 Season 2 ,您需要将视图模型上的 SeasonID 属性的值设置为 ID 第2季中的>:

So for you to select Season 2, you'd need to set the value of the SeasonID property on your view model to the ID of Season 2:

var viewModel = new SeasonViewModel
{
    SeasonID = // Season 2's SeasonID
}

但是,如果您直接绑定 select 的值,则像这样创建 select :

However, if you're not binding the value of the select directly, creating the select like this:

// Notice I've not specified `asp-for`.
<select class="form-control" asp-items="ViewBag.Seasons"></select>

将使用创建 SelectList 时设置的选定值.就是说,您目前执行此操作的代码略有错误.应该是:

will use the selected value you set when creating the SelectList. That said, your code to do that is currently slightly wrong. It should be:

var selected = _context.Seasons
    .Where(s => s.IsCurrent == true)
    .FirstOrDefault();
ViewData["Seasons"] = new SelectList(
                _context.Seasons,
                "ID",
                "SeasonName",
                // It needs to be the actual value of the field, not the season's object.
                selected?.ID.ToString());


简而言之,如果您想绑定到您的 SeasonID 属性,请创建您的 SelectList ,而不选择一个值,如下所示:


In short, if you want to bind to your SeasonID property, create your SelectList, without selecting a value, like so:

ViewData["Seasons"] = new SelectList(
            _context.Seasons,
            "ID",
            "SeasonName");

然后在视图模型本身上设置选定的值,其余的 asp-for 属性将完成其余工作.

Then set the selected value on the view model itself, and the asp-for attribute on the select will do the rest.