2014-09-03 285 views
9

我已將名和姓添加到ApplicationUser類。MVC User.Identity.Name,姓氏和名字

public class ApplicationUser : IdentityUser 
    { 
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
     { 
      // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
      var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
      // Add custom user claims here 
      return userIdentity; 
     } 

     public string FirstName { get; set; } 
     public string LastName { get; set; } 
    } 

還增加了信息RegisterViewModel

我的應用程序成功創建第一次和LastName表中,但我無法獲得姓和名作爲對_LoginPartial「User.Identity.Name」

顯示

回答

10

在partialview _LoginPartial.cshtml

添加代碼:

@if (Request.IsAuthenticated) 
{ 
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
    var user = manager.FindById(User.Identity.GetUserId()); 
... 
} 

ApplicationDbContext =您的DbContext - >默認:ApplicationDbContext

隨着ApplicationUser (user)的情況下,你可以得到First-LastName - 屬性

更換User.Identity.Nameuser.FirstName + " " + user.LastName這樣的:

<ul class="nav navbar-nav navbar-right"> 
    <li> 
     @Html.ActionLink("Hello " + user.FirstName + " " + user.LastName + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" }) 
    </li> 
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> 
</ul> 
+0

nope !,不給我「GetName」 – Emil 2014-09-03 12:53:01

+0

是正確的名字和姓氏? – 2014-09-03 13:01:59

+0

是的,但是「User.Identity」似乎沒有這些信息 – Emil 2014-09-03 13:12:18

3

你」當用戶登錄時,需要在用戶名稱中添加姓名。然後在您的視圖中訪問這些來自的聲明。看看幾乎相同的my answer here,只需要添加名稱而不是主題。