2013-11-15 31 views
2

新的MVC 5项目有_LoginPartial可显示当前用户名:获取当前ApplicationUser在PartialView

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", 
       "Manage", 
       "Account", 
       routeValues: null, 
       htmlAttributes: new { title = "Manage" }) 

我已经加入去年/名字字段ApplicationUser类,但不能找到一种方式来显示他们,而不是用户名。有没有办法访问ApplicationUser对象?我曾尝试直接铸造(ApplicationUser)User,但它会产生糟糕的转场异常。

回答

4
  1. 在MVC5,Controller.UserView.User,回报GenericPrincipal例如:

    GenericPrincipal user = (GenericPrincipal) User; 
    
  2. User.Identity.Name有用户名,你可以用它来获取ApplicationUser

  3. C#有扩展的不错的功能方法。探索和实验。

使用为例覆盖当前的问题有一定了解以下。

public static class GenericPrincipalExtensions 
{ 
    public static ApplicationUser ApplicationUser(this IPrincipal user) 
    { 
     GenericPrincipal userPrincipal = (GenericPrincipal)user; 
     UserManager<ApplicationUser> userManager = new UserManager<Models.ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
     if (userPrincipal.Identity.IsAuthenticated) 
     { 
      return userManager.FindById(userPrincipal.Identity.GetUserId()); 
     } 
     else 
     { 
      return null; 
     } 
    } 
} 
+0

我能够将它与出GenericPrincipal,导致抛出抛出异常。 – Sergi0

+0

@Sergi0太糟糕了,你不会分享你的解决方案。 –

+0

此代码不起作用,顺便说一句。 –

2

我做到了!

在这个环节使用帮助:http://forums.asp.net/t/1994249.aspx?How+to+who+in+my+_LoginPartial+cshtml+all+the+rest+of+the+information+of+the+user

我做了这样的:

在AcountController,添加一个动作来得到你想要的属性:

[ChildActionOnly] 
    public string GetCurrentUserName() 
    { 
     var user = UserManager.FindByEmail(User.Identity.GetUserName()); 
     if (user != null) 
     { 
      return user.Name; 
     } 
     else 
     { 
      return ""; 
     } 
    } 

而在_LoginPartialView,将原始行更改为:

@Html.ActionLink("Hello " + @Html.Raw(Html.Action("GetCurrentUserName", "Account")) + "!", "Index", "Manage", routeValues: new { area = "" }, htmlAttributes: new { title = "Manage" }) 
+0

如果你有一个特性,让我们说ChangeUserName在不同的视图中的不同部分,但共享相同的布局,如果数据更改_LoginPartialView更新? –

+0

如果我理解你的问题,你将不得不做一些Ajax更新视图。我的解决方案需要加载页面。 –

+0

这是我找到的最干净可读的解决方案。 – VSB