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
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);
}
[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);
}
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>
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>