Asp.net 如何从列表中的数据库获取数据<&燃气轮机;
net MVC,我搜索了太多的站点,无法将数据库中的数据提取到列表框中,但没有得到任何正确的答案 每个站点都有这样一个硬编码的列表示例Asp.net 如何从列表中的数据库获取数据<&燃气轮机;,asp.net,asp.net-mvc,Asp.net,Asp.net Mvc,net MVC,我搜索了太多的站点,无法将数据库中的数据提取到列表框中,但没有得到任何正确的答案 每个站点都有这样一个硬编码的列表示例 public SelectList GetAllCountryList() { List<Country> objcountry = new List<Country>(); objcountry.Add(new Country { Id = 1, CountryName = "India"
public SelectList GetAllCountryList()
{
List<Country> objcountry = new List<Country>();
objcountry.Add(new Country { Id = 1, CountryName = "India" });
objcountry.Add(new Country { Id = 2, CountryName = "USA" });
objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
return objselectlist;
}
public IQueryable<Country> GetCountries()
{
return from country in _db.Countries
orderby country.Name ascending
select country;
}
public SelectList GetAllCountryList()
{
List objcountry=新列表();
添加(新国家{Id=1,CountryName=“India”});
添加(新国家{Id=2,CountryName=“USA”});
添加(新国家{Id=3,CountryName=“巴基斯坦”});
添加(新国家{Id=4,CountryName=“Nepal”});
SelectList objselectlist=新的SelectList(objcountry,“Id”,“CountryName”);
返回objselectlist;
}
这个id是硬编码的,但我想从db获取它,我知道我必须应用查询
像这样
public List<Country> allname = new List<Country>
{
//query
};
public List allname=新列表
{
//质疑
};
但我不知道该怎么用,也不知道这是否正确
请帮助解决这个问题有两件事你需要知道
但对于数据访问,如果您使用的是实体框架,则许多人使用而不是实体框架
public class YouController:Controller
{
private YourDBContext db = new YourDBContext();
public SelectList GetAllCountryList()
{
var countries= db.Countries.ToList();
SelectList objselectlist = new SelectList(countries, "Id", "CountryName");
return objselectlist;
}
}
在存储库中,您可以这样创建
public SelectList GetAllCountryList()
{
List<Country> objcountry = new List<Country>();
objcountry.Add(new Country { Id = 1, CountryName = "India" });
objcountry.Add(new Country { Id = 2, CountryName = "USA" });
objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
return objselectlist;
}
public IQueryable<Country> GetCountries()
{
return from country in _db.Countries
orderby country.Name ascending
select country;
}
你想把这些都显示在视图中意味着
<%: Html.DropDownList("Countries" + i.ToString(), new SelectList(countries, "Id", "Name"))%>
希望你至少能有个主意。如何打数据库电话。您使用的存储库是什么?你在使用实体框架/任何/你自己的DAL吗?我在使用实体框架