2014-01-26 11 views
0

我甚至不知道我是怎麼來的字這個問題...自定義@ User.Identity.NewMethodHere()來的名字和姓氏返回用戶,使用EF代碼第一和asp.net的MVC

是使用新的asp.net身份提供者。我希望能夠從登錄用戶的某些數據中提取我網站的所有視圖。我的簡化模型是這樣的:

User.cs

public class User : IdentityUser 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    .... 
} 

在剃刀的意見,我得到檢查,看看是否有人登錄,然後使用:

@User.Identity.GetUserId() 

這顯然會返回我的用戶名。我想使我可以調用@ User.Identity.GetUserFirstAndLastName()或類似的方式。有沒有辦法添加這樣的電話?我真的很討厭必須爲ViewBag提供每個視圖的價值。

+1

看看[擴展方法](http://msdn.microsoft.com/en-us/library/bb383977.aspx)。 – wdosanjos

回答

0

感謝wdosanjos指向擴展方法。閱讀的鏈接,谷歌搜索更多一些後,我想出了這個:

public static class IdentityApplicationUserExtension 
{ 
    public static User GetApplicationUser(this IIdentity identity) 
    { 
     var manager = new UserManager<User>(new UserStore<User>(new MyDbContext())); 
     return manager.FindById<User>(identity.GetUserId()); 
    } 
} 

用戶是ApplicationUser類。

在Razor視圖所有我需要做的是這樣的:

@User.Identity.GetApplicationUser().AnyColumnFieldHere 

超級簡單畢竟!

相關問題