Search code examples
asp.netasp.net-coreviewforeign-keys

tutorial for fk in view dropdown asp.net


i am looking for a tutorial on how to put my foreign key in my create view as a dropdown or a way to select values from a different model. I have been trying a bunch of tutorials over the past few days and all of them end with an error and I am losing my mind. can anyone help me with a SIMPLE tutorial or show me how it's done?


Solution

  • put my foreign key in my create view as a dropdown

    Below is a work demo, you can refer to it:

    Equipment:

    public class Equipment
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [DisplayName("Equipment Name")]
            public string Name { get; set; }       
            [ForeignKey("DepartmentId")]
            public int DepartmentId { get; set; }
            public Department Department { get; set; }
        }
    

    Department:

    public class Department
        {
            [Key]
            public int Id { get; set; }
    
            [Required]
            [DisplayName("Department Name")]
            public string Name { get; set; }
            public ICollection<Equipment>? Equipment { get; set; }
        }
    

    EquipmentsController:

     // GET: Equipments/Create
            public IActionResult Create()
            {
                ViewData["DepartmentId"] = new SelectList(_context.Department, "Id", "Name");
                return View();
            }
    

    Equipment create view:

    <div class="form-group">
                    <label asp-for="DepartmentId" class="control-label"></label>
                    <select asp-for="DepartmentId" class ="form-control" asp-items="ViewBag.DepartmentId"></select>
                </div>
    

    result:

    enter image description here

    You can read one-to-many and Tutorial: Update related data - ASP.NET MVC with EF Core to know more.