puntapret
puntapret

Reputation: 201

MVC 5 show custom profile in shared layout

I'm just starting learning MVC 5, and i'm implementing the custom identity.

So i created this class :

public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string Email { get; set; }

    public string Avatar { get; set; }

}

Now my question seems really simple, but i spent hours without finding a solution.

What i want to do is display the custom user information in partial view.

In _Layout.cshtml, i have a partial view :

<div class="top-nav clearfix">
     @Html.Partial("UserInfo")
</div>

And what i want to do is display the custom properties Avatar in UserInfo.cshtml ?

<span class="username">@User.Identity.GetUserName()</span>
<span class="avatar">@?????forAvatar ?</span>

I've already tried to define the model in UserInfo.cshtml :

@model Models.ApplicationUser

// and using it like this in my view

<span class="avatar">@ViewData.Model.Avatar</span>

But it throw me an error when i click on Author page

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Models.Author]', but this dictionary requires a model item of type 'Models.ApplicationUser'.

Any help would be greatly appreciated.

Thanks

Upvotes: 0

Views: 3489

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

You'll have to ask the UserManager for an ApplicationUser object. For simplicity, we can stuff it in the ViewBag...

var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext());
var user = userManager.FindById(User.Identity.GetUserId());
ViewBag.CurrentUser = user;

(You need to add some using statements to bring in some namespaces, including Microsoft.AspNet.Identity and Microsoft.AspNet.Identity.EntityFramework)

And you should have access to it in your view...

<span class="avatar">@ViewBag.CurrentUser.Avatar</span>

Upvotes: 2

Related Questions