MVC6国家下拉列表 [英] MVC6 Dropdownlist of Countries
问题描述
我正在尝试使用MVC6标记帮助器创建CountryCode和CountryName的下拉列表,以便用户在注册后可以选择其国家/地区.到目前为止,视图的相关部分看起来像这样
I am trying to use MVC6 Tag Helpers to create a dropdownlist of CountryCode and CountryName so that a user can select their country after registering. The relevant part of the view looks like this so far
<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的相关部分如下所示
The relevant part of the viewmodel looks like this
[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; }
}
控制器将国家/地区列表返回到视图模型
The controller returns a list of countries to the viewmodel
var model = new IndexViewModel
{
CountryCode = user.CountryCode,
Countries =_customersContext.Countries.OrderBy(c=>c.CountryName),
};
return View(model);
}
但是在视图asp-items="@Model.Countries"
中有一个弯曲的Cannot convert Country to SelectListItem
but in the view asp-items="@Model.Countries"
has a squiggly Cannot convert Country to SelectListItem
我也找不到在表单中如何指定CountryCode作为要返回的属性以及CountryName作为要显示的属性.
Also I cannot find how in the form to specify CountryCode as the property to return and CountryName as the property to display.
推荐答案
除了在ViewModel中,属性的类型为SelectList
而不是IEnumerable<>
之外,我制作下拉菜单的方式有些相似.
The way I make my dropdowns is somewhat similar except that in my ViewModel, my property is of type SelectList
instead of an IEnumerable<>
.
public class HomeViewModel
{
public string CountryCode { get; set; }
public SelectList CountryList { get; set; }
}
然后在控制器中,我获取数据并将其转换为具有两个属性"Id"和"Value"的匿名列表.
Then in the controller I get the data and convert it to an anonymous list with two properties "Id" and "Value".
依次,我创建一个新的SelectList()
并传入匿名列表,该列表指定什么是dataValueField
和什么dataTextField
.
In turn, I create a new SelectList()
passing in the anonymous list specifying what is the dataValueField
and what is the 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);
}
最后,在视图中:
<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>
这篇关于MVC6国家下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!