2013-07-16 21 views
2

我有一個控制器傳遞的模型元素的數組,查看

public ActionResult UsersInRoles() 
    {   
     using (var ctx1 = new UsersModel()) 
     { 
      var model = new UsersInRolesViewModel(); 
      model.UserProfiles = ctx1.UserProfiles.ToList(); 
      model.UserRoles = ctx1.UserRoles.ToList(); 
      return View(model); 
     }    
    } 

我通過傳遞這兩個型號的我的看法: 包含的UserRole系統中所有可能我的角色。現在我需要在我的控制器中獲得一個用戶註冊的所有角色的數組,並將其傳遞給我,以便我可以知道不顯示用戶所在的可用角色框中的角色已經註冊。

我該怎麼做?

我看到兩個選項:

一些如何使用LINQ語句來嘗試和一氣呵成, 或 獲取數據傳遞經過的角色的完整模型,並和角色的用戶被註冊的陣列然後我能夠在視圖中顯示或者等等?

相關的usermodel AUX類:

public class UsersModel : DbContext 
{ 
    public UsersModel() 
     : base("name=UsersConnection") 
    {} 
    public DbSet<UserProfile> UserProfiles { get; set; } 
    public DbSet<Roles> UserRoles { get; set; } 
    public DbSet<UsersInRoles> UsersInUserRoles { get; set; } 
} 

public class UsersInRolesViewModel 
{ 
    public IList<UserProfile> UserProfiles { get; set; } 
    public IList<Roles> UserRoles { get; set; } 
    public IList<ut_GMUTempData> GMUTempData { get; set; } 
} 

回答

0

如果您只需要登錄用戶的角色,並使用Internet Application模板的默認簡單成員資格,則根本不需要模型綁定。您可以檢索的角色登錄的用戶在你看來這樣的:

@{ 
    // r will be a string[] array that contains all roles of the current user. 
    var r = Roles.GetRolesForUser();   
} 

,如果你想檢索任何其他用戶的角色,只是把用戶名到該方法:

@{ 
    // r will be a string[] array that contains all roles of the entered username. 
    var r = Roles.GetRolesForUser("username"); 
} 

在這種情況下,您只需將用戶名發送到您的模型。

更新:

如果你有用戶ID,您可以檢索用戶名,如下所示:

@{ 
    SimpleMembershipProvider provider = new SimpleMembershipProvider(); 
    string uname = provider.GetUserNameFromId(id); 

    // r will be a string[] array that contains all roles of the entered username. 
    var r = Roles.GetRolesForUser(uname); 
} 
+0

我需要使用第二個選項,但使用用戶ID而不是用戶名作爲用戶id是主鍵。 – Zapnologica

+0

我更新了我的答案以滿足您的需求。 – AminSaghi