I’m having trouble figuring out how to do this. The examples out there are not helping me understand what I need.
View Model
public class ViewModelAddUser
{
StudentSchedulingDBContext ssDB = new StudentSchedulingDBContext();
public User User { get; private set; }
public SelectList Departments { get; private set; }
public ViewModelAddUser()
{
// Not Sure what to put here
}
}
DBContext of Table (Just to show table structure in code)
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
}
Controller
public ActionResult AddUser()
{
return View(new ViewModelAddUser());
}
I’m not quite sure how to form the rest. I’ve been trying the nerddinner and other questions, but I’m not getting this to work.
Update
**View Model:**
public class ViewModelAddUser
{
public IEnumerable<SelectListItem> Departments { get; set; }
}
Controller:
public ActionResult AddUser()
{
ViewModelAddUser model = new ViewModelAddUser()
{
Departments = db.Departments.Select(department => new SelectListItem {
Value = department.DepartmentID.ToString(),
Text = department.DepartmentName
})
};
return View(model);
}
A View model should only contain the elements that will be used within the view. That shouldn’t include your db context. Likewise, make sure the user class you mention in the view model, is a view model for creating a user, and not your user domain model.
I think your view model should probably look something like :
To create the dropdownlist:
To call the drop down list:
Also check out the link Austin provided, Darin’s answer on that question might help you.