c# - 在下拉菜单中显示所有国家
问题描述
我正在注册城市,为此我想要一个国家的下拉菜单。数据在控制器上正确显示,但之后显示错误。
这是我的代码“模型视图”
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);
}
解决方案
你的页面.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>
推荐阅读
- python - 如何使用带有 x_train 和 y_train 变量数据的神经网络的 python 生成器?
- php - 不明白为什么我必须使用 json_decode 两次。Laravel 迁移和模型
- html - 带有小部件菜单的基于 Hugo 的网站也是下拉菜单?
- jquery - 传单 - 特征数据不会实时更新
- mysql - MySQL:子查询检查超过 14000 行的子查询优化问题
- spring-boot - 由于 lombok,Gradle 构建失败
- python - 将多列从 String 转换为 Float 和 Int
- node.js - 在 Mongoose 中更新嵌套对象
- javascript - Joi:根据其他键的值过滤值
- excel - VBA代码从工作表上的下拉菜单中选择值并转到与同一工作表上的标题具有相同值的列 - Excel 2010