在ASP.NET Core MVC中创建级联下拉列表可以有多种方式,这里我们通过从单个表中获取数据并使用Razor视图引擎来实现。下面是解决方法的步骤和示例代码:
步骤1:创建模型 首先,我们需要创建一个模型来表示表中的数据,包括父级和子级。在本例中,我们使用Country表,其中包含ID和Name字段。
public class Country
{
public int ID { get; set; }
public string Name { get; set; }
public int? ParentID { get; set; }
public Country ParentCountry { get; set; }
public List
步骤2:创建控制器 然后,我们需要创建一个控制器来获取数据并返回视图。在控制器中,我们将使用LINQ查询从数据库中获取Country数据,并将其传递给Razor视图。
public class HomeController : Controller { private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var countries = _context.Countries.Include(x => x.ChildCountries).Where(x => x.ParentID == null).ToList();
ViewBag.Countries = new SelectList(countries, "ID", "Name");
return View();
}
[HttpPost]
public IActionResult Index(int? parentCountryId)
{
if(parentCountryId == null)
{
return RedirectToAction("Index");
}
var selectedCountry = _context.Countries.Include(x => x.ChildCountries).FirstOrDefault(x => x.ID == parentCountryId);
ViewBag.Countries = new SelectList(_context.Countries.Where(x => x.ParentID == null).ToList(), "ID", "Name", selectedCountry.ParentID);
ViewBag.ChildCountries = new SelectList(selectedCountry.ChildCountries, "ID", "Name");
return View();
}
}
步骤3:创建视图 最后,我们需要创建Razor视图来显示父级和子级下拉列表。在视图中,我们将使用@Html.DropDownListFor辅助方法来呈现下拉列表,并将选定值传递给控制器。
@model Country
@{ ViewData["Title"] = "Cascading Dropdown Lists From Single Table - Razor View"; }
@using (Html.BeginForm()) {