尝试创建视图模型设计模式以填充DropdownList

时间:2012-04-27 18:52:26

标签: asp.net-mvc asp.net-mvc-3

我无法弄清楚如何做到这一点。那里的例子没有帮助我理解我的需要。

查看模型

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

1 个答案:

答案 0 :(得分:3)

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

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

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对该问题的回答可能对您有帮助。