我正在尝试使用 MVC6 Tag Helpers 创建一个 CountryCode 和 CountryName 的下拉列表,以便用户可以在注册后选择他们的国家。到目前为止, View 的相关部分看起来像这样
<form asp-controller="Manage" asp-action="EditCountry" asp-route-returnurl="@ViewData["ReturnUrl"]">
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<select asp-for="CountryCode" asp-items="@Model.Countries"></select>
viewmodel 的相关部分如下所示
[Display(Name = "Country")]
public string CountryCode { get; set; }
public IEnumerable<Country> Countries { get; set; }
一个国家看起来像这样
public partial class Country
{
[Key]
public string CountryCode { get; set; }
public string CountryName { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
}
Controller 将国家列表返回给 View 模型
var model = new IndexViewModel
{
CountryCode = user.CountryCode,
Countries =_customersContext.Countries.OrderBy(c=>c.CountryName),
};
return View(model);
但在 View 中 asp-items="@Model.Countries"
有一个波浪形的 Cannot convert Country to SelectListItem
我也找不到如何在表单中将 CountryCode 指定为要返回的属性并将 CountryName 指定为要显示的属性。
最佳答案
除了在我的 ViewModel 中,我的属性类型为 SelectList
外,我制作下拉菜单的方式有些相似。而不是 IEnumerable<>
.
public class HomeViewModel
{
public string CountryCode { get; set; }
public SelectList CountryList { get; set; }
}
然后在 Controller 中我获取数据并将其转换为具有两个属性“Id”和“Value”的匿名列表。
反过来,我创建一个新的 SelectList()
传入匿名列表,指定什么是 dataValueField
什么是 dataTextField
.
public IActionResult Index()
{
var countries = _customersContext.Countries.OrderBy(c => c.CountryName).Select(x => new { Id = x.Code, Value = x.Name });
var model = new HomeViewModel();
model.CountryList = new SelectList(countries, "Id", "Value");
return View(model);
}
最后,在 View 中:
<div class="form-group">
<label asp-for="CountryCode" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="CountryCode" asp-items="@Model.CountryList"></select>
</div>
</div>
关于c# - MVC6 国家下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738481/