Entity Framework and ASP.NET MVC 5 How can I push selected checkoxes into my localDB?

一曲冷凌霜 提交于 2021-02-20 04:45:25

问题


I am having troubles with pushing selected checkboxes into the table.

I have three tables - Employees, Projects and EmployeeProject. For one Employee I want to be able to choose multiple projects. I already created a create view with inputs for name of the employee and checkboxes of the projects. How can I send data to the EmployeeProjects table? So I could display it later.

My models:

public class Employee
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<EmployeeProject> EmployeesProjects { get; set; }
}

public class EmployeeViewModel
{
    public Employee Employee { get; set; }
    public List<SelectListItem> Projects { get; set; }
}

public class EmployeeProject
{
    [Key]
    public int Id { get; set; }   
    public int EmployeeId { get; set; }
    public int ProjectId { get; set; }
    public virtual Employee Employee { get; set; }
    public virtual Project Project { get; set; }
}

public class Project
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<EmployeeProject> EmployeesProjects { get; set; }
}

My Get Controller looks like that:

   [HttpGet]
        public ActionResult Create()
        {

            var employeeViewModel = new EmployeeViewModel
            {
                Employee = new Employee(),
                Projects = dbProject.Select()

My db for projects

 private readonly AppDbContext db;

        public SQLProjectData(AppDbContext db)
        {
            this.db = db;
        }
 public List<SelectListItem> Select()
        {
            return db.Projects.Select(p =>
               new SelectListItem
               {
                   Text = p.Name,
                   Value = p.Id.ToString()
               }).ToList(); 
        }

How should Post Controller look if i want to push new employee to employee table and for this employee and selected projects (each) i want to push id's to employeeproject table? In EmployeeViewModel I have a list of all projects and it works for Create View but in Details View I want only selected checkboxes.

Also all of employees and projects are created in app not in code so I don't have any hard coded values.

来源:https://stackoverflow.com/questions/65957641/entity-framework-and-asp-net-mvc-5-how-can-i-push-selected-checkoxes-into-my-loc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!