I have three entity classes:
namespace App.Data.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
public class Project
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class EmployeeProject
{
[Key]
public int Id { get; set; }
[ForeignKey]
public int EmployeeId { get; set; }
[ForeignKey]
public int ProjectId { get; set; }
public virtual Employee Employee{ get; set; }
public virtual Project Project { get; set; }
}
}
And one view model class
namespace App.Data.Models
{
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public List<SelectListItem> Projects { get; set; }
}
}
Right now I am able to add new employees and new projects. I am using localDB and Entity Framework. This is the link to my code https://github.com/IzaGorska/Project
What I want to do is to have checkbox for each project(need to have in mind that I don't have any hard coded projects - creating new project would mean extra checkbox) in EmployeeCreate view.
Also in EmployeeDetails view I want to display only checked projects. How can I do that?
I have db for employees and for project. Db for projects:
namespace App.Data.Services
{
public interface IProjectData
{
IEnumerable<Project> GetAll();
Project Get(int id);
void Add(Project project);
void Update(Project project);
}
public class InMemoryProjectData : IProjectData
{
List<Project> projects;
public void Add(Project project)
{
projects.Add(project);
project.Id = projects.Max(e => e.Id) + 1;
}
public void Update(Project project)
{
var exist = Get(project.Id);
if (exist != null)
{
exist.Name = project.Name;
exist.Description = project.Description;
}
}
public Project Get(int id)
{
return projects.FirstOrDefault(e => e.Id == id);
}
public IEnumerable<Project> GetAll()
{
return projects.OrderBy(e => e.Name);
}
}
public class SQLProjectData : IProjectData
{
private readonly AppDbContext db;
public SQLProjectData(AppDbContext db)
{
this.db = db;
}
public void Add(Project project)
{
db.Projects.Add(project);
db.SaveChanges();
}
public Project Get(int id)
{
return db.Projects.FirstOrDefault(p => p.Id == id);
}
public IEnumerable<Project> GetAll()
{
return from p in db.Projects
orderby p.Name
select p;
}
public void Update(Project project)
{
var entry = db.Entry(project);
entry.State = EntityState.Modified;
db.SaveChanges();
}
}
}
question from:
https://stackoverflow.com/questions/65905007/asp-net-mvc-5-checkbox-loop-for-new-created-values 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…