xivo
xivo

Reputation: 2054

Trying to Create a View Model Design Pattern to Populate DropdownList

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);  
    }

Upvotes: 0

Views: 485

Answers (1)

DMulligan
DMulligan

Reputation: 9073

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 :

public class ViewModelAddUser 
{
    public UserViewModel User { get; set; } //depending on what your doing a string containing UserId might suffice here
    public IEnumerable<SelectListItem> Departments { get; set; }
    public string DepartmentId { get; set; } // this will be the department set by drop down list
}

To create the dropdownlist:

StudentSchedulingDBContext ssDB = new StudentSchedulingDBContext(); //I'm assuming this can be queried to get your departments.
ViewModelAddUser model = new ViewModelAddUser()
{
    Departments = ssDB.Departments.Select(department => new SelectListItem {
         Value = department.departmentID,
         Text = department.departmentName
    }),
    User = //set user here if necessary
}

return View(model);

To call the drop down list:

@Html.DropDownListFor(m => m.DepartmentId, Model.Departments);

Also check out the link Austin provided, Darin's answer on that question might help you.

Upvotes: 3

Related Questions