Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current ApplicationUser in a PartialView

New MVC 5 project has _LoginPartial that display current username:

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

I have added last/first name fields to ApplicationUser class, but can't find a way to display them instead of UserName. Is there a way to access ApplicationUser object? I have tried straightforward casting (ApplicationUser)User but it generates bad cast exception.

like image 482
Sergi0 Avatar asked Jun 10 '26 14:06

Sergi0


2 Answers

  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.

Use below as example that cover some understanding for current question.

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;
        }
    }
}
like image 89
jd4u Avatar answered Jun 13 '26 04:06

jd4u


I did it!

Using the help in this link: http://forums.asp.net/t/1994249.aspx?How+to+who+in+my+_LoginPartial+cshtml+all+the+rest+of+the+information+of+the+user

I did it like that:

In the AcountController, add an action to get the property you want:

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

And in the _LoginPartialView, change the original line to this:

@Html.ActionLink("Hello " + @Html.Raw(Html.Action("GetCurrentUserName", "Account")) + "!", "Index", "Manage", routeValues: new { area = "" }, htmlAttributes: new { title = "Manage" })
like image 24
Ronen Festinger Avatar answered Jun 13 '26 04:06

Ronen Festinger