0

我很难弄清楚如何做到这一点。那里的例子并没有帮助我理解我需要什么。

查看模型

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(只是为了在代码中显示表结构)

public class Department
{
    public int DepartmentID { get; set; }
    public string DepartmentName { get; set; }
}

控制器

public ActionResult AddUser()
    {

        return View(new ViewModelAddUser());


    }

我不太确定如何形成其余部分。我一直在尝试 nerddinner 和其他问题,但我没有让这个工作。

更新

**View Model:**


public class ViewModelAddUser 
{
    public IEnumerable<SelectListItem> Departments { get; set; }
}

控制器:

public ActionResult AddUser()
    {
        ViewModelAddUser model = new ViewModelAddUser()
        {
            Departments = db.Departments.Select(department => new SelectListItem {
                Value = department.DepartmentID.ToString(),
                Text = department.DepartmentName
            })
        };
        return View(model);  
    }
4

1 回答 1

3

视图模型应该只包含将在视图中使用的元素。那不应该包括您的数据库上下文。同样,确保您在视图模型中提到的用户类是用于创建用户的视图模型,而不是您的用户域模型。

我认为您的视图模型应该看起来像:

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
}

创建下拉列表:

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

调用下拉列表:

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

另请查看 Austin 提供的链接,Darin 对该问题的回答可能会对您有所帮助。

于 2012-04-27T21:26:44.537 回答