未填充Asp.net剃刀下拉列表

时间:2020-02-17 14:54:09

标签: asp.net asp.net-core razor drop-down-menu combobox

我使用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

1 个答案:

答案 0 :(得分:1)

如果您想使用@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)