在使用DropDownList控件时,必须确保它的参数名参数不为null。以下是一个示例代码,展示如何正确使用DropDownList控件:
View:
Controller:
public IActionResult Create()
{
ViewBag.Cities = _context.Cities.ToList();
return View();
}
[HttpPost]
public IActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
_context.Employees.Add(employee);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
ViewBag.Cities = _context.Cities.ToList();
return View(employee);
}
在这个示例中,我们在Controller中的Create方法中将一个列表传递给View,并使用SelectList类创建一个SelectList。然后,在View中,我们使用DropDownList控件将这个SelectList呈现为一个下拉列表。这样,我们就可以正确使用DropDownList控件,避免了参数名为null的问题。