Question

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 !

Was it helpful?

Solution

View:

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

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

OTHER TIPS

You can use it like this.

@Html.DropDownList("Roles")

It will create the DropDownList for your ViewBag

You need to explicitly convert your ViewBag items to an expected type (IEnumerable<SelectListItem>), as ViewBag is a dynamic type

@Html.DropDownListFor(m => m.RoleId,((IEnumerable<SelectListItem>)ViewBag.Roles))

First look, it is showing you are trying to register the account. For that follow step by step procedure:

Register http get method add following line

ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");

Then HttpPost methods add following line:

ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");

In the register view add following line:

@Html.DropDownList("UserRoles", (SelectList)ViewBag.Name, " ")

I hope this will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top