gpt4 book ai didi

c# - MVC DropDownList 从一个数据库表填充并发送到另一个数据库表

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:15 25 4
gpt4 key购买 nike

我想要一个从资格表中提取数据的下拉列表,然后在 HttpPost 上它将下拉列表中选择的值存储到员工表的“资格”列中。我是 MVC 的新手,我不太了解语法。我也不知道如何使用 jquery、vb 等。很抱歉,如果有一篇文章涵盖了这一点,但我没有看到它,因为我不知道我在看什么。

这是我目前最好的尝试:

Controller :

private Database1Entities db = new Database1Entities();
...
...
...
// GET: /Home/CreateEmp
public ActionResult CreateEmp()
{
ViewBag.QualList = new SelectList(db.Qualifications, "Id", "qual");
return View();
}
// POST: /Home/CreateEmployee
[HttpPost, ActionName("CreateEmployee")]
public ActionResult CreateEmpResult(Employee emp)
{
if (ModelState.IsValid)
{
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QualList = new SelectList(db.Qualifications, "Id", "qual", emp.qualification);
return View(emp);
}

创建员工 View :

@model MvcDropDownList.Models.Employee
@using (Html.BeginForm("CreateEmployee", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table>
<!-- other fields removed for sake of simplicity -->
<tr>
<td>
@Html.Label("Select Your Qualification:")
</td>

<td>
@Html.DropDownList("QualList", "--Select--")
</td>
</tr>
</table>
}

表结构:

Qualifications Table: Id, qual

Employee Table: Id, firstName, surName, gender, qualification

我的代码成功地从“Qualification”表中获取数据,但没有将其发布到“employee”表中的“qualification”列。

如有任何建议,我们将不胜感激,谢谢!

最佳答案

您应该将下拉列表绑定(bind)到单击“保存”按钮时要返回的模型。

换句话说,这:

@Html.DropDownList("QualList", "--Select--")

应该变成这样:

@Html.DropDownListFor(model => model.Qualification_Id, (SelectList)ViewBag.QualList)

编辑 正如 Stephen Muecke 所指出的,您需要将 Viewbag 值转换为 SelectList

注意 DropDownListFor() 有多种可能性。为了清楚起见,我只选择了最简单的一个,但您可以添加可选标签等。

这会将它绑定(bind)到您的模型 (emp):

public ActionResult CreateEmpResult(Employee emp)

注意:如果您的 Employee 类已正确设置并具有所需的外键(链接到 Qualification 表),则应该已经有一个 。您的 Employee 类中的 Qualification_Id(或类似名称)(假设该类是您的实际数据库实体)。

这些更改将涵盖您需要的一切:

  • 下拉列表现在将所选值写入 emp.Qualification_Id
  • 在您的 Controller 方法中,您将 emp 保存到数据库中。
  • EF 将使用 FK 字段 (emp.Qualification_Id) 确保将正确的值写入将在数据库中创建的新员工行。

作为一般规则,始终尝试将控件(下拉列表、文本框等)绑定(bind)到模型的属性。如果这样做,则无需编写特定代码即可完成基本相同的操作。

关于c# - MVC DropDownList 从一个数据库表填充并发送到另一个数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28984916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com