C# 在asp.net mvc中加载页面时,如何从EF中的下拉列表中选择特定国家/地区
我使用EF从国家下拉列表中的数据库填充数据。我的下拉列表中有100多个国家 但我想在页面加载时选择一个特定的国家/地区C# 在asp.net mvc中加载页面时,如何从EF中的下拉列表中选择特定国家/地区,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我使用EF从国家下拉列表中的数据库填充数据。我的下拉列表中有100多个国家 但我想在页面加载时选择一个特定的国家/地区新西兰 你能告诉我怎么做吗 private static List<SelectListItem> GetCountries() { AayuDBEntities db = new AayuDBEntities(); List<SelectListItem> CountriesList =
新西兰
你能告诉我怎么做吗
private static List<SelectListItem> GetCountries()
{
AayuDBEntities db = new AayuDBEntities();
List<SelectListItem> CountriesList = (from p in db.Countries.AsEnumerable()
select new SelectListItem
{
Text = p.Name,
Value = p.Country_Id.ToString()
}).ToList();
return CountriesList;
}
照此
@Html.DropDownListFor(
m => m.CountryId, // Specifies where to store selected country Id
// It needs to be null for the default selection to work!
new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
"Id", // Use Country.Id as a data source for the values of dropdown items
"Name", // Use Country.Name as a data source for the text of dropdown items
13 // Specifies Australia (which has ID of 13) as the element selected by default
),
@Html.DropDownListFor(
m=>m.CountryId,//指定在何处存储选定的国家Id
//它需要为空,默认选择才能工作!
新的SelectList(Model.Countries,//IEnumerable,包含从数据库加载的所有国家/地区
“Id”,//使用Country.Id作为下拉项值的数据源
“Name”,//使用Country.Name作为下拉项文本的数据源
13//指定澳大利亚(其ID为13)作为默认选择的元素
),
遵循以下步骤
@Html.DropDownListFor(
m => m.CountryId, // Specifies where to store selected country Id
// It needs to be null for the default selection to work!
new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
"Id", // Use Country.Id as a data source for the values of dropdown items
"Name", // Use Country.Name as a data source for the text of dropdown items
13 // Specifies Australia (which has ID of 13) as the element selected by default
),
@Html.DropDownListFor(
m=>m.CountryId,//指定在何处存储选定的国家Id
//它需要为空,默认选择才能工作!
新的SelectList(Model.Countries,//IEnumerable,包含从数据库加载的所有国家/地区
“Id”,//使用Country.Id作为下拉项值的数据源
“Name”,//使用Country.Name作为下拉项文本的数据源
13//指定澳大利亚(其ID为13)作为默认选择的元素
),
这样做可能会有帮助。:)
这样做可能会有所帮助。:)您好。到目前为止你试过什么?请在发帖前回答问题。嗨。到目前为止你试过什么?发帖前请先确认。我不想使用
请选择。我想在页面加载时选择国家新西兰。OK@user11642353I不想使用请选择。我想在页面加载时选择国家新西兰。OK@user11642353it上面说,也有评论,你需要什么指南?我用不同的方式填充下拉列表中的数据,你用了不同的方式。上面说,也有评论,您需要什么指南?我使用不同的方法填充下拉列表中的数据,而您使用了不同的方法。
@Html.DropDownListFor(model => model.SlectedValue, Model.CountryList, "Please select", new { id = "ddlCity" })