Asp.net razor 下拉列表未填充

Asp.net razor dropdown list is not populated

我使用 Microsoft 的代码来本地化我的第一个 Web 应用程序。

我在这里看到列表不为空

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

但是下拉列表是空的

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home" 
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" 
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> <select name="culture"
          onchange="this.form.submit();"
          asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
        </select>
    </form>
</div>

这段代码有什么问题?

生成的 HTML 看起来像这样

    <div title="Request culture provider: AcceptLanguageHeaderRequestCultureProvider">
        <form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="/" method="post" class="form-horizontal" role="form">
            Language: <select name="culture" asp-for="de" asp-items="cultureItems"></select>
        </form>
    </div>

这是另一个也有同样问题的例子。 https://github.com/aspnet/Entropy/blob/master/samples/Localization.StarterWeb/Views/Shared/_SelectLanguagePartial.cshtml

如果您想使用@Html.DropDownList,请尝试使用以下代码:

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName ,Selected = (c.Name == requestCulture.RequestCulture.UICulture.Name )})
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}
<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home"
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label>

        @Html.DropDownList("culture", cultureItems, new
           {
               onchange = @"this.form.submit();"
           })

    </form>
</div> 

操作:

[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)