0

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 !

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Traffy
  • 2,803
  • 15
  • 52
  • 78
  • Go to http://www.asp.net/mvc/tutorials/older-versions/nerddinner/use-viewdata-and-implement-viewmodel-classes – Chirag Adhvaryu Mar 25 '14 at 09:10
  • 1
    This could prove very helpful for you... http://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-to-work – Paul Zahra Mar 25 '14 at 09:12

4 Answers4

3

View:

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

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

Murdock
  • 4,352
  • 3
  • 34
  • 63
0

You can use it like this.

@Html.DropDownList("Roles")

It will create the DropDownList for your ViewBag

ElectricRouge
  • 1,239
  • 3
  • 22
  • 33
0

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))
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
0

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.

Md Afjal
  • 16
  • 2