c# - MVC6 国家下拉列表

标签 c# asp.net-core asp.net-core-mvc

我正在尝试使用 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/

相关文章:

c# - ASP.NET Core依赖注入(inject): The Difference Between Factory and Instance?

c# - System.IO.Compression DLL 丢失且可能存在版本冲突

c# - 从 URL 中隐藏 Controller 名称

asp.net-core - 从 ActionFilterAttribute 设置 ViewBag

c# - 在 .net5/vNext/MVC6 中添加新的路由约束

c# - Microsoft Service Fabric 有状态服务无法启动

c# - 两次实现一个显式接口(interface)来实现 "virtual"行为是否是一个丑陋的 hack?

c# - 为什么使用 DSOFile 库设置的自定义文件属性在保存后不保留?

c# - .NET 4.5 和 .NET Core - 身份验证旧版

c# - 适用于 Windows x64 的 ASP.NET Core 应用程序(.NET Framework)仅在 project.assets.json 中出错