ASP.NET MVC将数据从数据库检索到DropDownList

时间:2016-07-08 13:30:12

标签: c# asp.net asp.net-mvc

我使用的是ASP.NET MVC Core,Entity Framework Core和SQL Server。我有以下列出的型号和控制器。一切正常,我能够使用精细的数据从我的数据库检索数据到我的DropDownList控件。

如果有人可以帮助我,我想知道是否有更好的方法来检索" public IActionResult Create()"我现在在EmployeeController中?

我想如果可能但不确定如何,创建2个名为public IActionResult DeptData()的方法和IActionResult BldgData()来检索那些方法的数据,然后将返回的数据传递给public IActionResult Create()方法EmployeeController而不是我现在的方式。

员工模型:

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

EmployeeController:

public class EmployeeController : Controller
{
    private DataEntryContext _context;

    public EmployeeController(DataEntryContext context)
    {
        _context = context;
    }

    // GET: /<controller>/
    public IActionResult Index()
    {
        return View(_context.Employees.ToList());
    }

    public string RetrieveDept()
    {
        var getDeptTitle = _context.Departments.ToList();
        SelectList Deptlist = new SelectList(getDeptTitle, "DeptId", "DeptTitle");
        ViewBag.DeptListName = Deptlist;

        return View(Create);
    }

    public IActionResult Create()
    {
        var getDeptTitle = _context.Departments.ToList();
        SelectList Deptlist = new SelectList(getDeptTitle, "DeptId", "DeptTitle");
        ViewBag.DeptListName = Deptlist;

        var getBldgTitle = _context.Buildings.ToList();
        SelectList Bldglist = new SelectList(getBldgTitle, "BldgId", "BldgName");
        ViewBag.BldgListName = Bldglist;

        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _context.Employees.Add(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">      
            <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">
            <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>

2 个答案:

答案 0 :(得分:0)

您可以做的一件事就是将代码包装起来,以便将下拉列表所需的项目转换为可以从其他操作方法调用的单独方法。

public IActionResult Create()
{
    ViewBag.DeptListName = GetDepartments();
    // Do the same for your other dropdown also
    return View();
 }
 private IEnumerable<SelectListItem> GetDepartments()
 {
      return context.Departments
                    .Select(s=> new SelectListItem { 
                                                     Value=s.DeptId.ToString(),
                                                     Text=s.DeptTitle })
                    .ToList();
 }

我个人更喜欢避免使用ViewBag和ViewData,并使用强类型视图模型将这些数据传递给视图。如果您感兴趣,Here是一篇解释如何操作的帖子。

答案 1 :(得分:0)

我建议使用部分视图。每个都有相关的下拉列表。

首先,我不建议使用ViewBag,而是强类型视图。因此,您的主视图需要接受MasterCreateViewModel,您需要创建一个同时具有BuildingsDepartments

的视图
class MasterCreateViewModel
{
    public List<Department> Departments { get; set; }
    public List<Building> Buildings { get; set; }
}

您的Master Create应该使用此ViewModel返回视图。

public IActionResult Create()
{
    var getDeptTitle = _context.Departments.ToList();
    var getBldgTitle = _context.Buildings.ToList();
    var viewModel = new MasterCreateViewModel()
                     {
                             Departments = getDeptTitle,
                             Buildings = getBldgTitle 
                     }

    return View(viewModel);
}

然后,您需要两个操作来返回具有相关下拉列表的部分视图。 E.g。

public IActionResult CreateDepartmentsPartial(List<Department> departments)
{
    return PartialView("CreateDepartmentsPartial", departments);
}

并且,局部视图也是:

<div class="form-group">
    <label asp-for="DeptId" class="col-md-2 control-label"></label>
    <div class="col-md-10">      
        <select asp-for="DeptId" asp-items="@Model" class="form-control"></select>  
        <span asp-validation-for="DeptId" 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>
@Html.RenderPartial("CreateDepartmentsPartial", Model.Departments)

P.S。:ASP.NET Core也有异步部分渲染。