且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何访问在布局文件中添加到ApplicationUser的模型属性

更新时间:2023-12-01 21:15:16

创建一个新的控制器,它将作为应用程序中所有控制器的基类(假设您已经在用户实例中保存了名字)

Create one new controller that will be base class for all all the controller in your application (Assuming that you have already saved firstname in user instance)

 public class ApplicationBaseController : Controller
        {
            protected override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                if (User != null)
                {
                    var context = new ApplicationDbContext();
                    var username = User.Identity.Name;

                    if (!string.IsNullOrEmpty(username))
                    {
                        var user = context.Users.SingleOrDefault(u => u.UserName == username);

                        ViewData.Add("firstName", user.FirstName);
                    }
                }
                base.OnActionExecuted(filterContext);
            }

            }

例如,HomeController继承如下的ApplicationBaseController:

For instance the HomeController inherits ApplicationBaseController as below:

  public class HomeController : ApplicationBaseController

现在使用以下代码更改登录部分:

Now change the login partial with below code :

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
           @Html.ActionLink("Hello " + (ViewData["firstName"]) + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}