How to access Model Property added to ApplicationU

2019-08-29 13:02发布

问题:

I am a beginner in ASP.Net MVC web development. And I want to know how can I access extra property added in my ApplicationUser model in layout file?

As of now if I have to access a property in the razor file I add @model myModel at top of Razor file and then I am able to access the property by @Model.MyProperty.

Suppose I added FirstName property in my Application User like below:

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

Now in my Login Partial I have 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 " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}

Suppose I also want to display FirstName instead of User.Identity.GetUserName() how can I do so.

Below is the RegisterViewModel which user will see during registration.

 public class RegisterViewModel
    {
        // rest property removed for brevity
        [Required]
        public string FirstName { get; set; }
    }

Now when a view is returned, the RenderBody() is the place where the actual CSHTML file related to that controller action gets rendered. But in my scenario I need to access the property of applicationUser in layout file which is common for all. Please guide me.

Can I do something like: User.Identity.GetFirstName or something along these lines?

回答1:

  1. Place your Login/Logout part in a separate view instead of inside your layout view.
  2. Then call an action (@Html.Action) from within the layout view to render the Login/Logout part. The action prepares the Login/Logout model and renders the separate view.

Using this approach allows you to pass a model to the view containing user specific informations.



回答2:

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);
            }

            }

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