ASP.NET MVC 检索数据库值到编辑时的下拉列表

本文关键字:编辑 下拉列表 NET MVC 检索 数据库 ASP | 更新日期: 2023-09-27 17:56:14

当我尝试"编辑"员工时,我在检索部门和建筑物的列表时遇到问题。我可以检索员工的名字和姓氏,但我在员工编辑视图上的部门和建筑物的下拉列表为空。请参阅下面的模型、控制器和视图。

员工模式:

public class Employee
{
    [Key]
    public int EmpId { get; set; }
    [Required]
    public string EmpFirstName { get; set; }
    [Required]
    public string EmpLastName { get; set; }
    public int DeptId { get; set; }
    public Department Department { get; set; }
    public int BldgId { get; set; }
    public Building Building { get; set; }
}

员工控制:

namespace DataEntryMVCEFCore.Controllers
{
    public class EmployeeController : Controller
    {
        private DataEntryContext _context;
        public EmployeeController(DataEntryContext context)
        {
            _context = context;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View(_context.Employees.ToList());
        }
        // Populate Department values to DropDownList
        private IEnumerable<SelectListItem> GetDepartments()
        {
            return _context.Departments
                          .Select(s => new SelectListItem
                          {
                              Value = s.DeptId.ToString(),
                              Text = s.DeptTitle
                          })
                          .ToList();
        }
        // Populate Building values to DropDownList
        private IEnumerable<SelectListItem> GetBuildings()
        {
            return _context.Buildings
                          .Select(s => new SelectListItem
                          {
                              Value = s.BldgId.ToString(),
                              Text = s.BldgName
                          })
                          .ToList();
        }
        public IActionResult Create()
        {
            // Load values to DropDownLists for Departments and Buildings for Create Method
            ViewBag.DeptListName = GetDepartments();
            ViewBag.BldgListName = GetBuildings();
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _context.Employees.Add(employee);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }
        public IActionResult Edit(int id)
        {
            var Employee = _context.Employees
                .Where(e => e.EmpId == id)
                .Single();
            return View(Employee);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _context.Employees.Update(employee);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }
    }
}

员工创建视图:

<form asp-controller="employee" asp-action="Create" method="post" class="form-horizontal" role="form">
<div class="form-horizontal">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="EmpFirstName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="EmpFirstName" class="form-control" />
            <span asp-validation-for="EmpFirstName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="EmpLastName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="EmpLastName" class="form-control" />
            <span asp-validation-for="EmpLastName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="DeptId" class="col-md-2 control-label"></label>
        <div class="col-md-10">      
            @*@Html.DropDownList("DeptList", ViewBag.DeptListName as SelectList, "Select Department")*@  
            <select asp-for="DeptId" asp-items="@ViewBag.DeptListName" class="form-control">
                <option>Please Select</option>
            </select>
            <span asp-validation-for="DeptId" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="BldgId" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            @*@Html.DropDownList("BldgList", ViewBag.BldgListName as SelectList, "Select Building")*@
            <select asp-for="BldgId" asp-items="@ViewBag.BldgListName" class="form-control">
                <option>Please Select</option>
            </select>
            <span asp-validation-for="BldgId" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

员工编辑视图:

<form asp-controller="employee" asp-action="Edit" method="post" class="form-horizontal" role="form">
    <div class="form-horizontal">
        <div asp-validation-summary="All" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="EmpFirstName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="EmpFirstName" class="form-control" />
                <span asp-validation-for="EmpFirstName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="EmpLastName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="EmpLastName" class="form-control" />
                <span asp-validation-for="EmpLastName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="DeptId" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                @*@Html.DropDownList("DeptList", ViewBag.DeptListName as SelectList, "Select Department")*@
                <select asp-for="DeptId" asp-items="@ViewBag.DeptListName" class="form-control"></select>
                <span asp-validation-for="DeptId" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="BldgId" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                @*@Html.DropDownList("BldgList", ViewBag.BldgListName as SelectList, "Select Building")*@
                <select asp-for="BldgId" asp-items="@ViewBag.BldgListName" class="form-control"></select>
                <span asp-validation-for="BldgId" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>

ASP.NET MVC 检索数据库值到编辑时的下拉列表

您的视图正在使用 ViewBag,您忘记将项目设置为 ViewBag.DeptListNameViewBag.BldgListName来呈现下拉列表。但是在您的编辑操作方法中,您没有设置这些(您在创建方法中这样做了)。

public IActionResult Edit(int id)
{
   var emp = _context.Employees.Where(e => e.EmpId == id).FirstOrDefault();
   if(emp==null)
       return View("NotFound"); //make sure you have this view.
   ViewBag.DeptListName = GetDepartments();
   ViewBag.BldgListName = GetBuildings();
   return View(emp );
}