'Associating foreign key on dropdown in Entity Framework Core

I am building a simple college management system where I have two models(right now). The following are my model classes.

public class FacultyModel
{
    [Key] 
    public int s_no { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string? file { get; set; }
    public string? hod { get; set; }
    public ICollection<ProgramModel> ProgramModels { get; set; }
}

public class ProgramModel
{
    [Key] 
    public int s_no { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string? file { get; set; }
   
    public string type { get; set; }
    public string system { get; set; }
    public string? director { get; set; }
    public int sem_year { get; set; }
    [ForeignKey("fid")]
    public FacultyModel faculty { get; set; }  
    public int fid { get; set; }
}

I have completed the CRUD operations for faculty. Now, While inserting the program(program model), I want the user to select one of the faculty from a dropdown or selectlist and the selected faculty's key will be set in the foreign key of program model. I'm stuck in this

Below is my controller of faculty model

public class AdminFacultyController : Controller
{
    private readonly DataContext _context;

    public AdminFacultyController(DataContext context, IWebHostEnvironment webHostEnvironment)
    {
        _context = context;
        _webHostEnvironment = webHostEnvironment;
    }

    private readonly IWebHostEnvironment _webHostEnvironment;

    // GET
    public async Task<string> UploadImage(string folderpath, IFormFile file)
    {
        folderpath += file.FileName;
        string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderpath);
        await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
        return "/" + folderpath;
    }

    public IActionResult Index()
    {
        var data = _context.FacultyModels.ToList();
        ViewBag.data = data;
        return View();
    }

    public IActionResult AddFaculty()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddFaculty(FacultyModel facultyModel, IFormFile file)
    {
        string folder = "file/";
        facultyModel.file = await UploadImage(folder, file);
        _context.FacultyModels.Add(facultyModel);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    public async Task<IActionResult> UpdateFaculty(int id)
    {
        var facultyModel= await _context.FacultyModels.FindAsync(id);
        ViewBag.data = facultyModel;
        return View(facultyModel);
        TempData["ID"] = id;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> UpdateFaculty( int id, FacultyModel facultyModel, IFormFile? file, string name, string description)
    {
        if (file == null)
        {
            var faculty = _context.FacultyModels.Where(f => f.s_no == id).FirstOrDefault();
            faculty.name = facultyModel.name;
            faculty.description = description;
            await _context.SaveChangesAsync();
        }
        else
        {
            string folder = "file/";
            facultyModel.file = await UploadImage(folder, file);
            _context.FacultyModels.Update(facultyModel);
            await _context.SaveChangesAsync();
        }

        return RedirectToAction("Index");
    }

    public IActionResult AppointHod()
    {
        return View();
    }

    public IActionResult UpdateHod()
    {
        return View();
    }

    public IActionResult DeleteFaculty(int id)
    {
         var data = _context.FacultyModels.Find(id);
         _context.FacultyModels.Remove(data);
         return RedirectToAction("Index");
    }
}

Below is my view containing selectlist for faculty

<form>
                         <div class="form-group">
                             <label for="input-1">Type</label>
                             <select class="form-control" id="input-1" placeholder="Enter type" name="type" required list="faculty">
                             <datalist id="faculty">
                                 <option > Bachelor </option>
                                 <option > Master</option>
                             </datalist>
                             </select>
                         </div>
                         
                         <div class="form-group">
                             <label for="input-2">Faculty</label>
                             <input type="text" class="form-control" id="input-2" placeholder="Enter semester/year" name="faculty" required list="teacher">
                             <datalist id="teacher">
                                 <option value="Boston"/>
                                 <option value="Cambridge"/>
                             </datalist>
                         </div>
                         
                         <div class="form-group">
                             <label for="input-3">Program Name</label>
                             <input type="text" class="form-control" id="input-3" placeholder="Enter Name" name="name" required>
                         </div>
                         <div class="form-group">
                             <label for="input-4">Description</label>
                             <input type="text" class="form-control" id="input-4" placeholder="Enter Description" name="description" required>
                         </div>
                         <div class="form-group">
                             <label for="input-5">File(syllabus)</label>
                             <input type="file" class="form-control" id="input-5" name="file">
                         </div>
                         <div class="form-group">
                             <div class="form-group">
                                 <label for="input-6">System</label>
                                 <select class="form-control" id="input-6" placeholder="Enter type" name="system" required list="system">
                                     <datalist id="system">
                                         <option > Yearly </option>
                                         <option > Semester</option>
                                     </datalist>
                                 </select>
                             </div>
                             <div class="form-group">
                                 <label for="input-7">Number of year/sem</label>
                                 <input type="number" class="form-control" id="input-7" placeholder="Enter number of year/sem" name="yearsem" required>
                             </div>
                             <button type="submit" class="btn btn-light px-5"> Add</button>
                         </div>
</form>

I just want to populate the selectlist with name of faculty and Insert the s_no of the selected faculty in program model as foreign key.



Solution 1:[1]

Below is a working demo, you can refer to it.

ProgramModel

 public class ProgramModel
    {
        [Key]
        public int ProgramModels_no { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string? file { get; set; }

        public string type { get; set; }
        public string system { get; set; }
        public string? director { get; set; }
        public int sem_year { get; set; }
       
        [ForeignKey("FacultyModels_no")]
        public virtual FacultyModel FacultyModel { get; set; }
        public int FacultyModels_no { get; set; }
    }

FacultyModel

public class FacultyModel
    {
        [Key]
        public int FacultyModels_no { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string? file { get; set; }
        public string? hod { get; set; }
        public virtual ICollection<ProgramModel> ProgramModels { get; set; }
    }

In Controller for ProgramModel, I add the below code in create action:

 ViewData["Faculty"] = new SelectList(_context.Set<FacultyModel>(), "FacultyModels_no", "name")

In the create view, I add like below:

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

result:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1