我正在尝试创建一个从数据库填充的下拉列表。我有:
public class Employee
{
[Key]
public int Id { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
[Required]
public String JobTitle { get; set; }
}
public class Project
{
[Key]
public int Id { get; set; }
[Required]
public String ProjectName { get; set; }
[Required]
public String CompanyName { get; set; }
}
public class ProjectHour
{
[Key]
public int Id { get; set; }
[Required]
public decimal Hours { get; set; }
[Required]
public DateTime Date { get; set; }
public virtual ICollection<Employee> employeeId { get; set; }
public virtual ICollection<Project> projectId { get; set; }
}
我想要的是创建一个表单,该表单将创建与项目和员工相关联的新项目时间。我正在尝试使用下拉列表在创建表单上显示员工和项目。显然,我对此完全陌生,但到目前为止我所拥有的是:
[HttpPost]
public ActionResult CreateProjectHour(ProjectHour newProjectHour)
{
using (var db = new TimesheetContext())
{
IEnumerable<SelectListItem> emp = db.Employees
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.LastName
});
ViewBag.EmployeeId = emp;
db.ProjectHours.Add(newProjectHour);
db.SaveChanges();
}
return RedirectToAction("ProjectHourList");
}
}
在表格上:
@model TimesheetMVC.Models.ProjectHour
...
@Html.DropDownListFor(model => model.employeeId, (SelectList)ViewBag.EmployeeId)
这显然是非常错误的。任何帮助将非常感激...!