MVC dropdown bind to a property of a property of the model

My Users model looks summing like this:

public class User { public int Id { get; set; } public string Username { get; set; } public string Password { get; set; } public Role Role { get; set; } } public class Role { public int Id { get; set; } public string Rolename { get; set; } } 

So when I create a new user, I want to select a Role from a dropdown list.

To do this on the view I have the following set up:

Controller

public ActionResult Create() { ViewBag.RoleId = new SelectList(db.Roles.ToList(), "Id", "Rolename"); return View(); } 

View

(now this is where I'm fuzzy)

@model Ortund.Models.User <div class="form-group"> @Html.LabelFor(model => model.Role.Id, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("RoleId", "Please select a User Role") @Html.ValidationMessageFor(model => model.Role.Id, "", new { @class="text-danger" }) </div> </div> 

This gives me an error because the User Model itself has no "RoleId" property but instead has the Role property which itself has the Id property which is what the dropdownlist should bind to – unless I'm mistaken.

So how the flap do I actually get this binding right?

Thanks in advance!

by ortund via /r/csharp

Leave a Reply