如何保存选定的列表项 [英] How to save selected list item
问题描述
我有一个包含以下列的Employee表:
EmployeeId,EmployeeName,DeptID,DesID,ReportingTo
在编辑视图中,我希望ReportingTo Column应该使用同一个表中的DropDownList项目来填充
EmployeeName。
我是能够在DropDownList上进行选择,但是所选的项目没有保存到数据库中,因此它显示为Null值。
如何保存所选项目?
谢谢,
在EmployeeController.cs
I have an Employee table with following Columns:
EmployeeId,EmployeeName,DeptID,DesID,ReportingTo
In Edit View,I want ReportingTo Column should get populated with DropDownList items of
EmployeeName from the same Table.
I am able to do the selection on DropDownList, but the selected Item is not getting saved into database,hence its showing Null value.
How to save the selected item ?
Thank You,
In EmployeeController.cs
// GET: /Employee/Edit/5
public ActionResult Edit(int id)
{
Employee employee = db.Employees.Find(id);
ViewBag.DeptID = new SelectList(db.Departments, "DeptID", "DeptShortDesc", employee.DeptID);
ViewBag.DesID = new SelectList(db.Designations, "DesID", "ShortDesc", employee.DesID);
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "EmployeeName", employee.EmployeeID);
return View(employee);
}
// POST: /Employee/Edit/5
[HttpPost]
public ActionResult Edit(Employee employee)
{
if (ModelState.IsValid)
{
db.Entry(employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DeptID = new SelectList(db.Departments, "DeptID", "DeptShortDesc", employee.DeptID);
ViewBag.DesID = new SelectList(db.Designations, "DesID", "ShortDesc", employee.DesID);
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "EmployeeName", employee.EmployeeID);
return View(employee);
}
在Edit.cshtml中
In Edit.cshtml
<div class="editor-label">
@Html.LabelFor(model => model.EmployeeID,"ReportingTo")
</div>
<div class="editor-field">
@Html.DropDownList("EmployeeID",string.Empty)
@Html.ValidationMessageFor(model => model.EmployeeID)
</div>
在Index.cshtml中
In Index.cshtml
<td>
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmpTypeID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.DeptShortDesc)
</td>
<td>
@Html.DisplayFor(modelItem => item.Designation.ShortDesc)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeName,"ReportingTo")
</td>
推荐答案
创建如下所示的类
Create a class like below
public static class DropDownList<T>
{
public static SelectList LoadItems(IList<T> collection, string value, string text)
{
return new SelectList(collection, value, text);
}
}
在编辑行动结果中设置员工
Set the employee in your Edit acion result
ViewBag.EmployeeId =
DropDownList<Employee>.LoadItems(
db.Employees, "EmpId", "Name");
查看代码
View code
@Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewBag.EmployeeId, new { @class = "select")
希望这有助于
Hope this helps
这篇关于如何保存选定的列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!