Search code examples
c#asp.net-mvcviewmodelhtml.dropdownlistforviewbag

DropDownList from Database using a viewmodel


I'm building an ASP.NET MVC 4 web app which allows to create users which have a role. There's two roles : Administrator and User. When a registration comes, the user can choose thanks to a dropdown list the role of the new user. So here's what I've done so far.

My UserViewModel :

public class UserModel
{
    [Required]
    [StringLength(50)]
    [Display(Name="Username : ")]
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [StringLength(50, MinimumLength=6)]
    [Display(Name = "Password : ")]
    public string Password { get; set; }


    public Role Role { get; set; }
}

And my HttpGet Method :

    [HttpGet]
    public ActionResult Registration()
    {
        context = new MainDatabaseEntities();
        ViewBag.Roles = new SelectList(context.Roles, "RoleId", "RoleDesc");
        return View();
    }

From here, I have no idea what I should do. Is my ViewModel good enough to do what I want (create and update an user)? How should I use my ViewBag.Roles into my Registration View?

Any help guys? I would appreciate it very much !


Solution

  • View:

    @Html.DropDownListFor(m => m.RoleId, (SelectList)ViewBag.Roles )
    

    You should have a RoleId in your model to save the selected item in.