Reputation: 535
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!
Upvotes: 0
Views: 2403
Reputation:
Forms post back the name/value pairs of their successful form controls. Your generating a <select>
element with name="RoleId"
but you model does not contain a property named RoleId
. Since you want to bind the selected option to the ApplicationRoleId
role property, then you view needs to be
@Html.LabelFor(m => m.ApplicationRoleId)
@Html.DropDownListFor(m => m.ApplicationRoleId, Model.ApplicationRoles)
@Html.ValidationMessageFor(m => m.ApplicationRoleId)
Notes:
@Html.Label(..)
code does not create a label
associated with your dropdownlist (clicking on it will not set
focus)ValidationMessageFor()
need to be applied to the property your
binding to, not the SelectList
ViewBag.RoleId = new SelectList(..)
code. Your have
already assigned the selectlist to the ApplicationRoles
property
(and you should never need ViewBag
if have a view model anyway)Upvotes: 1
Reputation: 89
Because you are declare that only HttpGet methods are allow in that method of the controller. Thats why
Upvotes: 0