2017-03-09 37 views
0

我試圖與一個以上的角色在這裏創建的用戶是我的新用戶創建在asp.net身份不止一個角色的用戶

public class UserForNewViewModel 
    { 
     public RegisterViewModel User { get; set; } 
     public List<IdentityRole> Roles { get; set; } 
    } 

這裏的ViewModel是我的行動

[HttpGet] 
    public async Task<ActionResult> Create() 
    { 
     var roles = await _context.Roles.ToListAsync(); 
     var model = new UserForNewViewModel() 
     { 
      Roles = roles 
     }; 
     return View(model); 
    } 

鑑於我如何能做到多角色

<div class="form-group"> 
      <label>Roles</label> 
      ??????????????????????????????????? 
      @Html.DropDownListFor(x => x.Roles., new SelectList(Model.Roles, "Id", "Name"), ("Seçin..."), new { @class = "form-control", id = "ParentId" }) 
     </div> 

enter image description here

回答

2

我有要求在用戶創建階段爲特定用戶添加多個用戶角色。

所以我要在前端實現這一目標使用複選框

所以這個的ViewPage

@model project_name.Models.RegisterViewModel 

@{ 

} 

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal"})) 
{ 

     <div class="form-group"> 
      <label class="col-md-2 control-label"> 
       Select User Role 
      </label> 
      <div class="col-md-10"> 
       @foreach (var item in (SelectList)ViewBag.RoleId) 
       { 
        <input type="checkbox" name="SelectedRoles" 
          value="@item.Value" class="checkbox-inline" /> 
        @Html.Label(item.Value, new { @class = "control-label" }) 
       } 
      </div> 
     </div> 

      .... 

      <div class="form-group"> 
       <div class="col-md-offset-2 col-md-10"> 
        <input type="submit" class="btn btn-default" value="Register" /> 
       </div> 
      </div> 
} 

這些都是我沒有在現有AspNet Identity 2.0 frameworkApp_Start文件夾中的變化=>IdentityConfig.cs文件

public class RoleManager<TRole> : RoleManager<TRole, string> where TRole : class, IRole<string> 
    { 
     // 
     // Summary: 
     //  Constructor 
     // 
     // Parameters: 
     // store: 
     public RoleManager(IRoleStore<TRole, string> store); 
    } 

     public class ApplicationRoleManager : RoleManager<ApplicationRole> 
     { 
      public ApplicationRoleManager(
       IRoleStore<ApplicationRole, string> roleStore) 
       : base(roleStore) 
      { 
      } 
      public static ApplicationRoleManager Create(
       IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) 
      { 
       return new ApplicationRoleManager(
        new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>())); 
      } 
    } 

這些是我在現有的AspNet Identity 2.0 frameworkModels摺疊ER =>IdentityModels.cs文件

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
     UserManager<ApplicationUser> manager) 
    { 
     var userIdentity = await manager.CreateIdentityAsync(
      this, DefaultAuthenticationTypes.ApplicationCookie); 
     return userIdentity; 
    } 
} 

    public class ApplicationRole : IdentityRole 
    { 
     public ApplicationRole() : base() { } 
     public ApplicationRole(string name) : base(name) { } 
     public string Description { get; set; } 
    } 

於是我已經設置了控制器的註冊方法如下

// POST: /Account/Register 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload, params string[] selectedRoles) 
    { 

     try 
     { 
      if (ModelState.IsValid) 
      { 
       var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };      


       var result = await UserManager.CreateAsync(user, model.Password); 

       if (result.Succeeded) 
       { 
        //Add User to the selected Roles 
        if (selectedRoles != null) 
        { 
         var addroles = await UserManager.AddToRolesAsync(user.Id, selectedRoles); 
         if (!addroles.Succeeded) 
         { 
          ModelState.AddModelError("", result.Errors.First()); 
          ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync("Name", "Name")); 
          return View(); 
         } 
        } 

       } 

       else 
       { 
        ModelState.AddModelError("", result.Errors.First()); 
        ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name"); 
        return View(); 
       } 

       return RedirectToAction("Index"); 
       // AddErrors(result); 
      } 

     } 

     // If we got this far, something failed, redisplay form 
     catch (RetryLimitExceededException /* dex */) 
     { 
      //Log the error (uncomment dex variable name and add a line here to write a log. 
      ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); 
     } 

     ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name"); 

     return View(model); 
    } 

但存在「RoleManager」字上面的控制器中的每一行,我收到編譯時錯誤如下面

使用通用類型 'RoleManager TRole,TKEY的' 需要2型 參數

這意味着我在上面的方法中得到了3個編譯時錯誤。

我也跟着this reference,才能認識到分配多個角色在ASPNET idenity用戶


編輯:

我只是改變IdentityRole.cs[MetaData]IdentityUserRole[MetaData]也如下

namespace Microsoft.AspNet.Identity.EntityFramework 
{ 
    // 
    // Summary: 
    //  Represents a Role entity 

    public class IdentityRole : IdentityRole<string, IdentityUserRole> 
    { 
     // 
     // Summary: 
     //  Constructor 
     public IdentityRole(); 
     // 
     // Summary: 
     //  Constructor 
     // 
     // Parameters: 
     // roleName: 
     public IdentityRole(string roleName); 
    } 

public class IdentityRole<TKey, TUserRole> : IRole<TKey> 
where TUserRole : IdentityUserRole<TKey> 
{ 
    public TKey Id 
    { 
     get 
     { 
      return JustDecompileGenerated_get_Id(); 
     } 
     set 
     { 
      JustDecompileGenerated_set_Id(value); 
     } 
    } 
    public string Name 
    { 
     get; 
     set; 
    } 
    public ICollection<TUserRole> Users 
    { 
     get 
     { 
      return JustDecompileGenerated_get_Users(); 
     } 
     set 
     { 
      JustDecompileGenerated_set_Users(value); 
     } 
    } 
    public IdentityRole() 
    { 
     this.Users = new List<TUserRole>(); 
    } 
} 

public class IdentityUserRole<TKey> 
{ 
    public virtual TKey RoleId 
    { 
     get; 
     set; 
    } 
    public virtual TKey UserId 
    { 
     get; 
     set; 
    } 
    public IdentityUserRole() 
    { 
    } 
} 
} 
+0

另一種選擇是在發佈時使用單個授權篩選器,但刪除內部報價。 [Authorize(Roles =「members,admin」)] –

0

你可以用複選框例如

<div class="col-md-10"> 
      @foreach (var item in (SelectList)ViewBag.RoleId) 
      { 
       <input type="checkbox" name="SelectedRoles" 
         value="@item.Value" class="checkbox-inline" /> 
       @Html.Label(item.Value, new { @class = "control-label" }) 
      } 
     </div>