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.
In MVC5, Controller.User and View.User, returns are GenericPrincipal instance:
GenericPrincipal user = (GenericPrincipal) User;
User.Identity.Name has username, you can use it to retrieve the ApplicationUser
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;
}
}
}
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With