我试图从 MVC 中的下拉列表中检索值,我能够从表中绑定(bind)下拉列表,但无法将所选下拉值的 ID 保存回数据库。
//The following is a snippet of my Create.aspx
<%= Html.dropdownlist("departments", "Select One")%>
//The following is a snippet of my HomeController.cs
public ActionResult Create()
{
this.ViewData["departments"] = new SelectList(_service.ListDepartments(), "departmentID", "name");
return View("Create");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(int? deptID, [Bind(Exclude = "educationID")] tblEDA empToCreate)
{
if (_service.CreateEmp(deptID, empToCreate))
return RedirectToAction("Index");
return View("Create");
}
我们将不胜感激任何帮助。
最佳答案
将您的 deptID
参数名称更改为 departments
。
MVC 中的参数与发布/路由数据相匹配。因为您正在创建一个名称为“departments”的 DropDownList,这是表单元素的名称。提交数据时,没有名为deptID
的数据,只有departments
。
我还将 deptID
设为 int
(与 int?
相对),除非它实际上是可选的。
关于c# - MVC C# 中的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2175304/