在PartialView中获取当前ApplicationUser

3
新的MVC 5项目有一个_LoginPartial文件,用于显示当前用户名:
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", 
                 "Manage", 
                 "Account", 
                 routeValues: null, 
                 htmlAttributes: new { title = "Manage" })

我已经在ApplicationUser类中添加了姓和名字段,但无法找到一种方法将它们显示而不是UserName。有没有一种方法可以访问ApplicationUser对象?我尝试了直接转换 (ApplicationUser)User 但它会生成错误的类型转换异常。

2个回答

4
  1. In MVC5, Controller.User and View.User, returns are GenericPrincipal instance:

    GenericPrincipal user = (GenericPrincipal) User;
    
  2. User.Identity.Name has username, you can use it to retrieve the ApplicationUser

  3. C# has nice feature of extension methods. Explore and experiments with it.

以下内容可作为示例,涵盖了一些与当前问题相关的理解。

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;
        }
    }
}

我能够在没有使用GenericPrincipal的情况下使用它,因为那个转换会抛出错误的转换异常。 - Sergi0
@Sergi0 真遗憾你没有分享你的解决方案。 - Ronen Festinger

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" })

如果您在不同的视图中有一个名为ChangeUserName的功能,但共享相同的布局,则数据更改时_LoginPartialView是否会更新? - william e schroeder
如果我理解你的问题,你需要做一些ajax来更新视图。我的解决方案需要加载页面。 - Ronen Festinger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接