首页 > 解决方案 > 在下拉菜单中显示所有国家

问题描述

我正在注册城市,为此我想要一个国家的下拉菜单。数据在控制器上正确显示,但之后显示错误。

这是我的代码“模型视图”

public class CountryCityViewModel
{
  public int CountryId { get; set; }
  public string name { get; set; }
  public SelectList CountryList { get; set; }
  public string CountryListId{ get; set; }
}

'城市控制器'

public async Task<IActionResult> Create()
{
  var result = await _countryService.GetAllCountriesCity();
  ViewBag.Cities = result;
  return View(result);
}

'HTML'

<div class="form-group col-sm-6">
 @Html.LabelFor(model => model.CountryId, "Country", htmlAttributes: new { @class = "control-label col-md-2" })
 @Html.DropDownList(, new SelectList(ViewBag.Cities, "CountryId", "Name"))
 @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>

“城市服务班”

public async Task<IEnumerable<CountryCityViewModel>> GetAllCountriesCity()
{
  var uri = $"{_siteConfiguration.ApiBaseUrl}{ApiEndPoint.Get_Countries_All}";        
  var response = _httpClient.GetAsync(uri).Result;
  var contents = response.Content.ReadAsStringAsync().Result;
  var result = JsonConvert.DeserializeObject<IEnumerable<CountryCityViewModel>>(contents);
  return await Task.FromResult(result);
}

标签: c#htmlsql-serverasp.net-mvc-3.net-core

解决方案


你的页面.cshtml

@{
    var list = _countryService.GetAllCountriesCity().Select(x => new SelectListItem()
               {
                   Value = x.CountryId.ToString(),
                   Text = x.Name
               }).ToList();
}
<select asp-items="@list" asp-for="CountryId" class="form-control"></select>

推荐阅读