Vag*_*gue 12 c# asp.net-core-mvc asp.net-core
我正在尝试使用MVC6 Tag Helpers创建CountryCode和CountryName的下拉列表,以便用户在注册后可以选择他们的国家/地区.到目前为止,视图的相关部分看起来像这样
<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>
Run Code Online (Sandbox Code Playgroud)
viewmodel的相关部分看起来像这样
[Display(Name = "Country")]
public string CountryCode { get; set; }
public IEnumerable<Country> Countries { get; set; }
Run Code Online (Sandbox Code Playgroud)
国家看起来像这样
public partial class Country
{
[Key]
public string CountryCode { get; set; }
public string CountryName { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器将视图模型返回国家/地区列表
var model = new IndexViewModel
{
CountryCode = user.CountryCode,
Countries =_customersContext.Countries.OrderBy(c=>c.CountryName),
};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
但在视图中asp-items="@Model.Countries"有一个波浪形Cannot convert Country to SelectListItem
另外,我无法在表单中找到如何将CountryCode指定为要返回的属性,并将CountryName指定为要显示的属性.
Vli*_*nce 46
我的下拉菜单的方式有点相似,只是在我的ViewModel中,我的属性是类型SelectList而不是IEnumerable<>.
public class HomeViewModel
{
public string CountryCode { get; set; }
public SelectList CountryList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中我获取数据并将其转换为具有两个属性"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);
}
Run Code Online (Sandbox Code Playgroud)
最后,在视图中:
<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>
Run Code Online (Sandbox Code Playgroud)