-1

I have one to many relationship in the application. I want to display data in the view using ViewBag, but instead of data from the database I get the path name of the model class. My code:

public class Department
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
    public ICollection<Instructor> Instructor { get; set; }
}

    [Key]
    public int InstructorId { get; set; }
    public string NameInstructor { get; set; }
    public string Email { get; set; }
    public string ScienceDegree { get; set; }
    public Department Department { get; set; }

Controller class:

[HttpGet]
    public ActionResult Create()
    {
        var item = db.Departments.ToList();
        ViewBag.DepartmentName = new SelectList(item, "DepartmentName");
        return View();
    }

View class:

@Html.DropDownList("DepartmentName", new SelectList(ViewBag.DepartmentName, "DepartmentName"))

As a result, I get it instead of names. I also did according to guides, step by step but it does not help, unfortunately I have no idea what to do. enter image description here

Antero00
  • 113
  • 1
  • 1
  • 6
  • 1
    `ViewBag.DepartmentName = new SelectList(item, "DepartmentName", "DepartmentName");` and `@Html.DropDownList("DepartmentName", (SelectList)ViewBag.DepartmentName)` but refer also [Can the ViewBag name be the same as the Model property name in a DropDownList?](https://stackoverflow.com/questions/37161202/can-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist) –  Nov 14 '18 at 21:46
  • https://stackoverflow.com/questions/35755862/why-i-am-getting-system-web-mvc-selectlistitem-in-my-dropdownlist this might help as well. – Clinton Cochrane Nov 14 '18 at 21:49

2 Answers2

1

You will need to add SelectListItem to your SelectList not the actual departments list. You can either iterate over your list, convert each item to a SelectListItem which you can then add to your SelectList or use a generic method. Example (considering your departments list containts two properties called ID and Name, if not you may change them according to your needs):

public static List<System.Web.Mvc.SelectListItem> GenerateSelectList<T>(this IEnumerable<T> itemsToBeAppended)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (T itemToBeAppended in itemsToBeAppended)
        {
            SelectListItem item = new SelectListItem();
            var type = itemToBeAppended.GetType();

            item.Value = type.GetProperty("ID").GetValue(itemToBeAppended).ToString();
            item.Text = type.GetProperty("Name").GetValue(itemToBeAppended).ToString();
            items.Add(item);
        }
        return items.OrderBy(x => x.Text).ToList();
    }
Sorin87bv
  • 156
  • 8
0

Please try DepartmentId instead of DepartmentName

@Html.DropDownList("DepartmentId", new SelectList(ViewBag.DepartmentName, "DepartmentName"))