c# - MVC C# 中的下拉列表

标签 c# asp.net-mvc

我试图从 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/

相关文章:

asp.net-mvc - 如何防止 "Swapping"或 "Staged"Azure 网站注销用户?

c# - WCF流式文件传输

c# - WPF TabControl Position Tabs 在右上角

c# - cshtml C#已经存在一个与此连接相关联的打开的DataReader,必须先关闭它

asp.net-mvc - MVC3 中带有两个可选参数的路由不起作用

asp.net-mvc - 如何在不重复代码的情况下实现业务和 View 验证?

javascript - 折线图生成的图像将通过电子邮件发送

c# - 我应该在 MVC 编码中使用什么标准

c# - 通过mvvmcross进行非线性导航

c# - 有没有办法编写一个表示构造函数参数的表达式?