C# MVC6国家/地区下拉列表
我正在尝试使用MVC6标记帮助程序创建CountryCode和CountryName的下拉列表,以便用户在注册后可以选择他们的国家。到目前为止,视图的相关部分是这样的C# MVC6国家/地区下拉列表,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,我正在尝试使用MVC6标记帮助程序创建CountryCode和CountryName的下拉列表,以便用户在注册后可以选择他们的国家。到目前为止,视图的相关部分是这样的 viewmodel的相关部分如下所示 [显示(Name=“Country”)] 公共字符串CountryCode{get;set;} 公共IEnumerable国家{get;set;} 一个国家看起来像这样 公共部分类国家/地区 { [关键] 公共字符串CountryCode{get;set;} 公共字符串CountryNa
viewmodel的相关部分如下所示
[显示(Name=“Country”)]
公共字符串CountryCode{get;set;}
公共IEnumerable国家{get;set;}
一个国家看起来像这样
公共部分类国家/地区
{
[关键]
公共字符串CountryCode{get;set;}
公共字符串CountryName{get;set;}
公共虚拟ICollection用户{get;set;}
}
控制器将国家/地区列表返回给viewmodel
var model = new IndexViewModel
{
CountryCode = user.CountryCode,
Countries =_customersContext.Countries.OrderBy(c=>c.CountryName),
};
return View(model);
但是在视图asp items=“@Model.Countries”
中有一个扭曲的无法将国家/地区转换为SelectListItem
此外,我无法在表单中找到如何将CountryCode指定为要返回的属性,将CountryName指定为要显示的属性。我创建下拉列表的方式有些类似,只是在我的ViewModel中,我的属性的类型是
SelectList
,而不是IEnumerable
然后在控制器中,我获取数据并将其转换为具有两个属性“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);
}
最后,我们认为:
<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>
公共类MyViewModel//模型层
{
public int CountryId{get;set;}
公共字符串CountryName{get;set;}
公共列表EmployeesList{get;set;}
}
公营雇员
{
公共int Id{get;set;}
公共字符串全名{get;set;}
}
public IActionResult Contact1()//控制器
{
MyViewModel N1=新的MyViewModel();
列表N2=新列表()
{
新员工{Id=1,FullName=“sivaragu”},
新员工{Id=2,FullName=“siva”},
新员工{Id=3,FullName=“SENTHIL”}
};
ViewBag.MovieType=N2;
返回视图();
}
CSHTML(MVC6)
我已经提出了一种替代方法,通过扩展带有更多属性的
SelectTagHelper
,可以使这种类型的开发更加方便。讨论了这个问题
它基于一个类SelectListDescriptor
,该类包含项目列表、分别显示文本和值字段的属性。然后在视图中显示一个简单类型
--选择此CSHTML代码所在的国家/地区
<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>
public class MyViewModel //MODEL LAYER
{
public int CountryId { get; set; }
public string CountryName { get; set; }
public List<Employee> 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<Employee> N2 = new List<Employee>()
{
new Employee { Id=1,FullName="sivaragu" },
new Employee { Id=2,FullName="siva" },
new Employee { Id=3,FullName="SENTHIL" }
};
ViewBag.MovieType = N2;
return View();
}
<select asp-for="CountryId" asp-items="@(new SelectList(@ViewBag.MovieType,"Id","FullName") )">
</select>