I can get all Roles plus actually Role for chosed user, but then When I posting to EditUser action, then Dropdownlist sends null. I mean When the form posts to my controller, I get null from DropDownList.
Here is my Model
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
public string ApplicationRoleId { get; set; }
}
Here is Action
[HttpGet]
public async Task<ActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = RoleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await UserManager.FindByIdAsync(id);
if (user != null)
{
var role = await UserManager.GetRolesAsync(user.Id);
var existingRole = role.First();
string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
model.Id = user.Id;
model.FirstName = user.FirstName;
model.ApplicationRoleId = existingRoleId;
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
}
}
return PartialView("_EditUser", model);
}
And here is DropDownlist from _EditUser.cshtml
<div class="form-group">
@Html.Label("Role typ", htmlAttributes: new { @class = "control-label col-md-6" })
<div class="col-md-12" title="Ange antal datorer som finns i lager">
@Html.DropDownList("RoleId", null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ApplicationRoles, "", new { @class = "text-danger" })
</div>
</div>
Getting null Only from DropDownList, not from @Html.EditorFor /Thanks in advance!
RoleId? - based on the code in your get method your view code will be@Html.DropDownListFor(m => m.ApplicationRoleId, Model.ApplicationRoles)