我可以查看任何人的记录,然后可以编辑它,如果我点击记录下面的编辑按钮,点击后会转到另一个显示文本框和下拉列表的页面,复选框可以编辑,所有文本框都包含EmpID
的值但问题是我想要在DROPDOWN LIST中预先选择的值,就像它应该为每个用户选择相应的值,如我的文本框一样。
我正在使用Linq-to-SQL,ASP.NET MVC 3和C#
代码:
@using EmployeeAttendance_app.Models
@model IEnumerable<GetEmployeeEditDetails_SpResult>
@{
var Item = Model.FirstOrDefault();
}
<style type="text/css">
</style>
<div>
@using (Html.BeginForm("EditEmployee", "Home", FormMethod.Get))
{
<label id="lblName" class="editEmp_label">Name</label>
<input type="text" value= @Item.EmplName name="EmpName" placeholder="Update Name" />
<br />
<label id="lblDept" class="editEmp_label">Department</label>
@Html.DropDownList("DeptID", @Item.DeptName)
<br />
<label id="lblShift" class="editEmp_label">Shift</label>
@Html.DropDownList("ShiftId")
控制器:
public ActionResult EditEmployee()
{
if (!String.IsNullOrEmpty(Session["Admin"] as string))
{
int? EmplId = Convert.ToInt32(Session["EmpEdit"]);
IEnumerable<GetEmployeeEditDetails_SpResult> EmployeeValues = DataContext.GetEmployeeEditDetails_Sp(EmplId).ToList();
var DepNames = (from n in DataContext.HrDepts select new { n.DeptID, n.DeptName }).Distinct();
ViewData["DeptID"] = new SelectList(DepNames, "DeptID", "DeptName");
var ShiftNames = (from n in DataContext.AtdShifts select new { n.ShiftId, n.ShiftName }).Distinct();
ViewData["ShiftId"] = new SelectList(ShiftNames, "ShiftId", "ShiftName");
return View(EmployeeValues);
}
}
答案 0 :(得分:0)
如果要为DropDownList创建预定义的选定值,最简单的方法是在SelectList()中定义所选值。所以你可以在控制器中执行此操作:
ViewData["DeptID"] =
new SelectList(DepNames,
"DeptID", // Value
"DeptName", // Text
EmployeeValues.FirstOrDefault().DepId); // selected value
同样在您的视图中,您需要使用@ Html.DropDownList,如下所示:
@Html.DropDownList("DeptID", (SelectList)ViewData["DeptID"])
我建议您在使用html帮助程序类时,阅读更多关于intellisense的文档或提示。