MVC 5在共享布局中显示自定义配置文件 [英] MVC 5 show custom profile in shared layout

查看:118
本文介绍了MVC 5在共享布局中显示自定义配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习MVC 5,并且正在实现自定义身份.

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

所以我创建了这个课:

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.

在_Layout.cshtml中,我有一个局部视图:

In _Layout.cshtml, i have a partial view :

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

我想做的是在UserInfo.cshtml中显示自定义属性Avatar?

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>

我已经尝试在UserInfo.cshtml中定义模型:

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

传递到字典中的模型项的类型为'System.Collections.Generic.List`1 [Models.Author]',但是此字典需要模型项为'Models.ApplicationUser'.

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'.

任何帮助将不胜感激.

谢谢

推荐答案

您必须向UserManager请求一个ApplicationUser对象.为简单起见,我们可以将其填充到ViewBag ...

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;

(您需要添加一些using语句以引入一些名称空间,包括Microsoft.AspNet.IdentityMicrosoft.AspNet.Identity.EntityFramework)

(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>

这篇关于MVC 5在共享布局中显示自定义配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆