【问题标题】:Show All Countries in Drop down menu在下拉菜单中显示所有国家
【发布时间】:2020-05-26 12:50:32
【问题描述】:

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

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

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# html sql-server asp.net-mvc-3 .net-core


【解决方案1】:

YourPage.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>

【讨论】:

  • 1.这个问题没有说明他们在现有代码中遇到的问题(除了模糊地提到“错误”)。回答低质量的问题会降低网站的质量。更糟糕的是,我们无法在不知道问题的情况下确定您的答案是否正确。 2. 这个答案没有解释当前解决方案有什么问题,或者你的新代码如何解决这个问题。
  • 您似乎没有阅读我的评论。既然您显然对 OP 的问题有更详细的了解,您能告诉我 OP 用 “但之后它显示错误。” 指的是什么错误吗?为什么这些错误是由 OP 的当前代码引起的?您的代码如何修复它们?
猜你喜欢
  • 1970-01-01
  • 2012-05-06
  • 2011-10-13
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 2018-06-03
  • 2013-08-08
  • 2021-12-23
相关资源
最近更新 更多