我在SO中提到了类似的问题,但无法对此进行排序。所以请不要认为是重复的。 Link1 Link2
ViewModel:
public class UserAssignRoleViewModel
{
[Required(ErrorMessage = "Please select a User")]
public string Username { get; set; }
[Required(ErrorMessage = "Please select a Role")]
public string Role { get; set; }
public IEnumerable<SelectListItem> Users { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
Controller ActionMethod
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserName, string Role)
{
AppUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context));
userManager.AddToRole(user.Id, Role);
ViewBag.ResultMessage = "Role Assigned successfully !";
var model = new UserAssignRoleViewModel();
var users = context.Users.ToList();
model.Users = users.Select(s => new SelectListItem
{
Value = s.UserName,
Text = s.UserName
});
var roles = context.Roles.ToList();
model.Roles = roles.Select(s => new SelectListItem
{
Value = s.Name,
Text = s.Name
});
return View(model);
}
查看
@model ERPLite.Models.UserAssignRoleViewModel
@using (Html.BeginForm("RoleAddToUser", "Role"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>
@Html.ValidationMessageFor(model => model.Username)
User Name: @Html.DropDownListFor(u =>u.Username , (IEnumerable<SelectListItem>)Model.Users, "--Select--")
@Html.ValidationMessageFor(model => model.Role)
Role Name: @Html.DropDownListFor(r =>r.Role, (IEnumerable<SelectListItem>)Model.Roles, "--Select-- ")
</p>
<input type="submit" value="Save" />
}
单击按钮时,验证永远不会触发。 感谢任何帮助,提前感谢。