Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am new to Entity Framework with MVC
I created my model classes Faculty and Department.
C#
public class Faculty
  {
      [Key]
      public int FacultyID { get; set; }

      [Required(ErrorMessage = "Enter Faculty Name")]
      [Display(Name = "Faculty Name")]
      public string FacultyName { get; set; }

      public virtual ICollection<Department> Departments { get; set; }
  }

C#
public class Department
   {
       [Key]
       public int Id { get; set; }

       //[Required(ErrorMessage ="Enter Department ID")]
       //[Display(Name ="Department ID")]
       //public string departmentID { get; set; }

       [Required(ErrorMessage = "Enter Department Name")]
       [Display(Name = "Department Name")]
       public string DepartmentName { get; set; }

       public virtual Faculty Faculty { get; set; }


       [Required(ErrorMessage = "Select Faculty")]
       [Display(Name = "Faculty")]
       public int FacultyID { get; set; }
   }

So i generated a view for the two models
The field for faculty id in create department looks like this.
<div class="form-group">
            @Html.LabelFor(model => model.FacultyID, "FacultyID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("FacultyID", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.FacultyID, "", new { @class = "text-danger" })
            </div>
        </div> 




So how do i use the viewbag to display the list of faculties in the dropdownlist in the view? Thanks

What I have tried:

I tried to use Viewbag in the Department Create action
C#
public ActionResult Create()
        {
            ViewBag.FacultyID = new SelectList(db.Faculties, "FacultyID", "FacultyName");
            return View();
        }
Posted
Updated 27-Aug-16 1:32am

I would recommend passing this via model. Also, I don't think you can use SelectList in MVC for DropDownListFor, i think you have to use a List of SelectListItem (or IEnumerable).

So the syntax for DropDownListFor can be something as simple as this

C#
@Html.DropDownListFor(m=>m.Name, new List<SelectListItem>(), new{@class="form-control"})


m=>m.Name is the property name for your model and new List<selectlistitem> is your collection of items to display in the drop down. But notice, if you are not using a model in your view, you can't use DropDownListFor, instead, simply DropDownList will work as it is not strongly typed.

C#
@Html.DropDownList("Name", new List<SelectListItem>(), new{@class="form-control"})


A more working example would be something similar to the following

Controller Action

C#
public ActionResult Index()
        {
            var list = new List<People>();
            list.Add(new People { Name = "David" });
            list.Add(new People { Name = "Thom" });

            var selectList = new List<SelectListItem>();

            foreach (var item in list)
            {
                selectList.Add(new SelectListItem { Text = item.Name, Value = item.Name});
            }

            return View(selectList);
        }


View - Index.cshtml

HTML
@model IEnumerable<SelectListItem>

@{
    ViewBag.Title = "Home Page";
}


@Html.DropDownList("Name", Model, new{@class="form-control"})


But to use viewbag, you would do the same thing, but instead of model you just do

Controller

C#
public ActionResult Index()
        {
            var list = new List<People>();
            list.Add(new People { Name = "David" });
            list.Add(new People { Name = "Thom" });

            var selectList = new List<SelectListItem>();

            foreach (var item in list)
            {
                selectList.Add(new SelectListItem { Text = item.Name, Value = item.Name});
            }

            ViewBag.Items = selectList;

            return View();
        }


HTML
@Html.DropDownList("Name", ViewBag.Items, new{@class="form-control"})
 
Share this answer
 
v2
Quote:
Rightly directed by David_Wimbley, creating strongly typed view is good to go for...


In case interested in using strongly typed view follow 3 steps as below;
1. create a viewmodel that will hold Department and Faculty list
C#
public class DepartmentViewModel
    {
        public Department Department { get; set; }
        public List<Faculty> Faculty { get; set; }
    }



2. Controller will be
C#
public ActionResult Create()
        {
            //assuming faculty list is created somewhere else
            var DepartmentViewModel = new DepartmentViewModel { Faculty=faculties};
            return View(DepartmentViewModel);
        }


3. and view will be (if needed this dropdown list can also be created as partial view)
@model DropDownListDemo.Models.DepartmentViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.DropDownListFor(model => model.Department.FacultyID, new SelectList(Model.Faculty, "FacultyID", "FacultyName"));
    </div>
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900