简体   繁体   English

下拉列表自动变成多个

[英]Drop-down list automatically becomes multiple

Can anyone explain why my drop-down list automatically allows multiple selections?谁能解释为什么我的下拉列表会自动允许多选?

I'm quite new to Net Core and this is the first time I add a drop-down and I'm obvisouly doing something wrong.我对 Net Core 很陌生,这是我第一次添加下拉菜单,而且我显然做错了什么。 Everything works technically, the drop-down list is populated and the Model gets the correct data when posting but for some reason the multiple attribute is automatically set for the drop-down list.从技术上讲,一切正常,下拉列表被填充,模型在发布时获得正确的数据,但由于某种原因,下拉列表会自动设置多个属性。

View看法

<select asp-for="@Model.fooForm.CountryRows"
        asp-items="@(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
        class="form-control">
    <option>Please select Country of use</option>
</select>

ViewModel视图模型

namespace foo.Models.ViewModels
{
    [Bind(Prefix = nameof(fooIndexRootVM.fooForm))]
    public class fooVM
    {
        public fooVM()
        {
        }

        public fooVM(CountryVM[] countryRows)
        {
            CountryRows = countryRows;
        }

        [Display(Name = "Country of use")]
        public virtual CountryVM[] CountryRows { get; set; }
    }
}

Controller/Service控制器/服务

public async Task<fooIndexRootVM> GetCountries()
{
    var countryRows = await fooContext.Country
        .OrderBy(c => c.CountryCode)
        .Select(c => new CountryVM
        {
            CountryCode = c.CountryCode
            ,CountryName = c.CountryName
            ,CountryBlocked = c.CountryBlocked
        })
        .ToArrayAsync();

    return new fooIndexRootVM
    {
        fooForm = new fooVM(countryRows)
    };
}

From MSDN: The select tag helper来自MSDN:选择标签助手

The Select Tag Helper will automatically generate the multiple = "multiple" attribute if the property specified in the asp-for attribute is an IEnumerable.如果 asp-for 属性中指定的属性是 IEnumerable,则 Select Tag Helper 将自动生成 multiple = "multiple" 属性。

So in your case the model it's looking at represents a list for asp-for="@Model.fooForm.CountryRows" .因此,在您的情况下,它正在查看的模型表示asp-for="@Model.fooForm.CountryRows"

In order to fix this you can add new property for selected country to model为了解决这个问题,您可以为所选国家/地区添加新属性以进行建模

public virtual CountryVM SelectedCountry { get; set; }

Then asp-for should be like this:那么asp-for应该是这样的:

<select asp-for="@Model.fooForm.SelectedCountry"
        asp-items="@(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
        class="form-control">
    <option>Please select Country of use</option>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM