MVC6国家下拉列表

我正在尝试使用MVC6 Tag Helpers创建CountryCode和CountryName的下拉列表,以便用户在注册后可以选择他们的国家/地区。 到目前为止,视图的相关部分看起来像这样

viewmodel的相关部分看起来像这样

  [Display(Name = "Country")] public string CountryCode { get; set; } public IEnumerable Countries { get; set; } 

国家看起来像这样

  public partial class Country { [Key] public string CountryCode { get; set; } public string CountryName { get; set; } public virtual ICollection Users { get; set; } } 

控制器将视图模型返回国家/地区列表

  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

另外,我无法在表单中找到如何将CountryCode指定为要返回的属性,并将CountryName指定为要显示的属性。

我的下拉菜单的方式有点类似,只是在我的ViewModel中,我的属性是SelectList类型而不是IEnumerable<>

 public class HomeViewModel { public string CountryCode { get; set; } public SelectList CountryList { get; set; } } 

然后在控制器中我获取数据并将其转换为具有两个属性“Id”和“Value”的匿名列表。

反过来,我创建了一个新的SelectList()传递在匿名列表中,指定dataValueField是什么以及dataValueField是什么。

 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); } 

最后,在视图中:

 
 public class MyViewModel //MODEL LAYER { public int CountryId { get; set; } public string CountryName { get; set; } public List EmployeesList { get; set; } } public class Employee { public int Id { get; set; } public string FullName { get; set; } } public IActionResult Contact1() //CONTROLLER { MyViewModel N1 = new MyViewModel(); List N2 = new List() { new Employee { Id=1,FullName="sivaragu" }, new Employee { Id=2,FullName="siva" }, new Employee { Id=3,FullName="SENTHIL" } }; ViewBag.MovieType = N2; return View(); } 

CSHTML(MVC6)

  

我已经提出了另一种方法,通过扩展SelectTagHelper以及一些可以使这种类型的开发更方便的属性。 这个问题在这里讨论。

它基于一个类SelectListDescriptor ,它包含项列表,分别显示文本和值字段的属性。 然后在视图中一个简单的类型

国家描述符只是new SelectListDescriptor(nameof(Country.CountryCode), nameof(Country.CountryName), countries) 。 这通过利用`nameof-operator的力量来避免魔术字符串