在ASP.NET MVC中连接两个详细信息到下拉列表的解决方法可以通过以下步骤来实现:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet Countries { get; set; }
public DbSet Cities { get; set; }
//...
}
public ActionResult Create()
{
var countries = db.Countries.ToList();
var cities = db.Cities.ToList();
ViewBag.CountryList = new SelectList(countries, "Id", "Name");
ViewBag.CityList = new SelectList(cities, "Id", "Name");
return View();
}
@Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "Select Country", new { @class = "form-control" })
@Html.DropDownListFor(model => model.CityId, ViewBag.CityList as SelectList, "Select City", new { @class = "form-control" })
注意:这里假设你的视图模型中有一个CountryId和CityId属性来存储用户选择的值。
这样,当用户访问Create视图时,将会显示一个包含国家和城市下拉列表的表单。用户可以从下拉列表中选择相应的国家和城市。